In clpmisc, individual FAQ entries get regularly posted to the group: really, by our brian d foy. Specifically one that was recently posted (link @ GG) is How do I find the first array element for which a condition is true? to which some poster, "MrL22", replied:
# Do this using GREP my @people = ('Jacob Smith', 'Michael Brown', 'Joshua Smith', 'Matthew Cope'); @smiths = grep(/smith/i, @people);
Then of course several of us replied to the effect that
In particular, my followup said:
No! my $first = (grep /smith/i, @people)[0]; But inefficient, because it will grep more than necessary.
And here comes the pearl, which is Anno Siegel's further followup and which I'm reporting hereafter.
Here's the relevant part of Anno's post, with some formatting added:
I prefer to write that
my ( $first) = grep ...;It can easily be combined with a check for uniqueness, which is sometimes an issue:
my @l = qw( foo bar baz); ( my ( $first) = grep /ba/ => @l ) > 1 and warn "not unique\n"; print "first: $first\n";
Now, I'm also repeating here what I've already written in the original thread: although the behaviour of list assignment in scalar context is well known to me, as is every single bit of syntax and semantics used here, I wouldn't have thought of that, and to do the same thing I would have probably concocted something more clumsy and not just as terse and readable. I suppose that many here are already familiar with the "technique", but I hope it will be of benefit to those that aren't.
BTW: we had recently had again in clpmisc a long, exhausting, often pitaful but in some corners interesting (sub-)thread (link @ GG) vastly dealing exactly with contexts, and lists, and list assignment.
In reply to Cool example of list assignment usage by blazar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |