Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: assign multiple values of a key in hash to multiple variable

by davido (Archbishop)
on Aug 21, 2013 at 05:26 UTC ( #1050282=note: print w/replies, xml ) Need Help??

in reply to assign multiple values of a key in hash to multiple variable

This...: "@nnnumber_of_file_low" interpolates an array into a string. It's similar to: join q{ }, @nnnumber_of_file_low;. So you aren't actually putting multiple values into the hash elements. You're putting a single scalar into each hash element.

Then you say my( $value1, $value2 ) = $nn_file{$key};, but since $nn_file{$key} only contains a single scalar value, what you're really saying is something similar to my ($value1, $value2) = ( $nn_file{$key}, undef );.

So when you print "key is $key value is $value1 $value2";, you're really saying something like: print "key is ((some key)) value is ((some value)) ((undef))";. Perl complains when you interpolate an undefined value into a string, because that's usually a mistake, as it is here. It's only by virtue of Perl's DWIMery that undef stringifies to an empty string. And it's warnings that warns you about it.

Hash elements are scalar values, as are array elements. If you want to store more than one thing in a hash element, you have to store a reference to another container. Recommended reading: perlreftut, perldsc, perllol, and perlref.

As an example of what you probably intend to do:

my %hash; $hash{some_key} = [ $this, $that ]; # [ ... ] creates an anonymous ar +ray ref. $hash{other_key} = [ $the, $other ]; # and that is assigned to the has +h. foreach my $key ( keys %hash ) { print "key: $key, values: $hash{$key}[0], $hash{$key}[1]\n"; }


Replies are listed 'Best First'.
Re^2: assign multiple values of a key in hash to multiple variable
by rahulruns (Beadle) on Aug 21, 2013 at 05:56 UTC

    Thank You Dave for the explanation. I did sort out the solution by introducing split and thus resolving the undef issue

    my ($value1,$value2) = split (' ', $nn_file{$key});

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1050282]
[Eily]: as in "I might have inverted two, but my eyes misread in the some order as my fingers mistype"
[LanX]: can't find a definition for the sound
[LanX]: Voiceless_palatal_ fricative
[Eily]: Lanx https://en. wiki/Voiceless_pal atal_fricative
Eily got the Cowboy message
[Your Mother]: I prefer palatial fricatives.
[Lotus1]: https://en. wiki/%C3%87
[Your Mother]: I'm headed out west, sucker.
[Lotus1]: the west is the best, get here we'll do the rest
LanX chjuman !

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (18)
As of 2017-03-27 17:04 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.