in reply to Re: passing @ to sub and getting back hash
in thread passing @ to sub and getting back hash

Not quite so simple. Better would be:

my %hash2 = map {/^ "xxxx-(\d+):xxxxxx([^,]+),.+"$/ ? ($1 => $2) : ( +)} @data;

Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^3: passing @ to sub and getting back hash
by jwkrahn (Abbot) on Jan 01, 2008 at 03:30 UTC
    How would that be "better"?
    $ perl -MData::Dumper -le' my @dc = ( "xxxx-123:xxxxxxABC,z", "xxxx-:xxxxxx,z", "xxxx-456:xxxxxx, +z", "xxxx-XXX:xxxxxxDEF,z", "xxxx-789:xxxxxxGHI,z" ); my %hash1 = map /^xxxx-(\d+):xxxxxx([^,]+),.+$/, @dc; my %hash2 = map { /^xxxx-(\d+):xxxxxx([^,]+),.+$/ ? ($1 => $2) : () } +@dc; print Dumper \%hash1, \%hash2; ' $VAR1 = { '123' => 'ABC', '789' => 'GHI' }; $VAR2 = { '123' => 'ABC', '789' => 'GHI' };
      Grandfather's statement is better because it gracefully(and explicitly) handles the case where the regex does not match.

           "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

        My New Year's resolution is to remember (from Regexp Quote Like Operators):

        If the /g option is not used, m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3...). (Note that here $1 etc. are also set, and that this differs from Perl 4's behavior.) When there are no parentheses in the pattern, the return value is the list (1) for success. With or without parentheses, an empty list is returned upon failure.

        My version simply does explicitly what jwkrahn's code does implicitly. So 'better' is a function of remembering the match operator's behavior in list context, which for some reason (probably to do with skull thickness) I seem to have trouble doing.


        Perl is environmentally friendly - it saves trees
Re^3: passing @ to sub and getting back hash
by convenientstore (Pilgrim) on Jan 01, 2008 at 02:00 UTC
    thanks guys, my script works like a charm, but Grandpa's map statement is very stylish(i put it into my /etc/motd for now) thanks!!!!