Matthew Rochlin wrote:
> Find the element no of the last element of a grep match?
> That's pretty much the scalar output of grep.
> e.g.
> @list = qw(ham pig barn dog hammer lost);
> $nofound = @found = grep {/ham/} @list;
> print @found[$nofound-1]; # $nofound-1 should index to the last found
> I'm a newbie, so forgive me if I've absolutely missed the point.
You have. You're calling grep in list context here (because you're assigning
to @found), so grep returns two elements, qw(ham hammer). @found is then
assigned to the scalar $nofound, which receives the number 2, since @found
has two elements.
So $found[$nofound-1] is $found[1], which is the last element -- but if
you're just interested in the last element, you might as well use $found[-1]
or $found[$#found] and dispense with the variable $nofound.
grep in scalar context does return the number of entries matched (in this
case, 2), but you can only use this as an index into the return value of
grep in list context -- $found[1] makes sense but $list[1] does not. You
don't know the index *in the array @list* where the last match was found,
which is what I believe the OP wanted.
(Oh, and don't write @found[$nofound-1] here, since that's an array slice
and you're only interested in one element.)
Cheers,
Philip
---
You are currently subscribed to perl-win32-users as: [archive@jab.org]
To unsubscribe, forward this message to
[EMAIL PROTECTED]
For non-automated Mailing List support, send email to
[EMAIL PROTECTED]