convenientstore has asked for the wisdom of the Perl Monks concerning the following question:

I thought I could pass the array to the sub and get back a hash right into another hash but obviously it's wrong.

Is this where I have to use reference to pass it back?
sub sub1 { my %enc; for (@_) { chomp; if ( $_[0] =~ /^ "xxxx-(\d+):xxxxxx([^,]+),.+"$/ ) { $enc{$1} = $2; } else { next; } } } %hash1 = sub1(@dc);

Replies are listed 'Best First'.
Re: passing @ to sub and getting back hash
by Joost (Canon) on Dec 31, 2007 at 21:04 UTC
Re: passing @ to sub and getting back hash
by ysth (Canon) on Dec 31, 2007 at 21:05 UTC
    Can you describe what you want to do in English? Looping over @_ but checking $_[0] in your loop makes not a lot of sense. Did you mean $_ instead?

    "Return a hash" seems to mean different things to different people. Maybe you want return %enc;, which actually returns a list of alternating keys and values, not a hash at all, or maybe you want to return \%enc;, which returns a hashref. In either case, the caller needs to know what is going to come back and be doing the right thing with it. Your caller example is expecting a list, not a hashref.

      $_ was the problem, let me fix it in and get back to you guys.
      You guys are the best!! thanks.
Re: passing @ to sub and getting back hash
by runrig (Abbot) on Dec 31, 2007 at 21:05 UTC
    You need to return the hash (how else is the sub supposed to know what you want to return?).
Re: passing @ to sub and getting back hash
by jwkrahn (Abbot) on Dec 31, 2007 at 21:22 UTC
    You don't really need a sub to do that:
    my %hash1 = map /^ "xxxx-(\d+):xxxxxx([^,]+),.+"$/, @dc;

      Not quite so simple. Better would be:

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

      Perl is environmentally friendly - it saves trees
        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' };
        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!!!!