[Pdx-pm] hash from array question
Eric Wilhelm
scratchcomputing at gmail.com
Sat May 26 02:07:41 PDT 2007
# from Thomas Keller
# on Friday 25 May 2007 10:55 pm:
> my @index = grep {
> my $c = $_;
> if ($c > $#lines or # always false
> ( grep { $lines[$c] =~ m/$_/ } @names ) > 0 )
> { 1; #yes, select it
> } else {
> 0; # no, skip it
> }
> } 0..$#lines;
This was kind of bugging me, so I looked it up. Note the original
snippet is already suffering from a sort of illustrative clarity:
my @bigger_indices = grep {
if($_ > $#y or $x[$_] > $y[$_]) {
1;
} else {
0;
}
} 0..$#x;
This reduces to:
my @bigger_indices = grep({$_ > $#y or $x[$_] > $y[$_]} 0..$#x);
(And the book actually does that just down the page, though it then goes
on to suggest using map but reverts back to the if/else rather than a
ternary.)
So, firstly always be wary of "if($expr) {1} else {0}" code, (and this
is somewhat awkwardly hiding a ternary ($expr ? 1 : 0) which is much
more obviously just ($expr). The important point being that the return
value of the block handed to grep is true or false.
Secondly, whenever a book introduces a function, read perldoc to really
grok how it works outside the context of the book's example.
Finally, use of if/else for implicit return values is just bad.
I think the "always false" comment must be because that is a vestigial
bit leftover from the original example.
Speaking of comments, it's important to realize that books have to be
more commenty than production code. They're trying to teach. You just
need to remind yourself and other programmers why the lines need to be
whittled out from the file.
--Eric
--
"If you only know how to use a hammer, every problem begins to look like
a nail."
--Richard B. Johnson
---------------------------------------------------
http://scratchcomputing.com
---------------------------------------------------
More information about the Pdx-pm-list
mailing list