[Israel.pm] (no subject)

Shlomi Fish shlomif at iglu.org.il
Sun Oct 22 08:55:01 PDT 2006

I'll answer your question but first a few remarks on your style:

On Sunday 22 October 2006 12:39, Yossi Itzkovich wrote:
> Hi,
> Let's say I have a function  :
> 1 sub filterByField

Personally I dislike studlyCaps identifier names. Underscore-separated names 
are much more readable. But that's just me.

> 2 { # find in the given array of hashes(==records) , thoese who have
> hash key $fieldName that equals to $fieldValue

"those *that* have" or "those *which* have". "Who" is reserved for people.

> 3 my ($fieldName,$fieldValue,$arrOfHashes)=@_;
> 4 my @retVal=grep ({defined $$_{$fieldName} and $$_{$fieldName} eq
> $fieldValue} @$arrOfHashes);

Better use $_->{$fieldName} instead of $$_{$fieldName}. It's more readable, 
and easier to understand.

> 5 }
> currently the call is like:
> 6 my @handle=filterByField("User Name","Moshe");
> It works, but it is limited, for example, for multiple conditions, or
> regex.
> I want to pass a code ref to that function, I will do the changed in
> filterByField, and I will send the code block in line 4 as the code ref.
> Question:  Should  $_ in the code block  really getd the iterator value
> in grep for each iteration ?



use strict;
use warnings;

sub cond
    return scalar($_ =~ /h/);

print join(",", 
    grep { cond(); } 
        (qw(the quick cheshire fox jumped over the lazy dog and hurdles))
), "\n";

This prints:


The function call itself preserves the value of "$_" that was 
dynamically-scoped-wise (i.e: "local" in Perl) set in grep. Of course it 
would be better and safer to pass the value explictly and shift it out of the 
callback call.


	Shlomi Fish

Shlomi Fish      shlomif at iglu.org.il
Homepage:        http://www.shlomifish.org/

Chuck Norris wrote a complete Perl 6 implementation in a day but then
destroyed all evidence with his bare hands, so no one will know his secrets.

More information about the Perl mailing list