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

Hi monks, is it possible to use something like this?
while (<FILE>) { chomp; my ($key, $rest) = split /-/; push @{$hash{$key}},$rest; } $l=14178439; @values= exists $hash{$l}? @hash{$l}:undef; { print "\n Hash Value of 14178439 : @{$hash{$l}} \n"; }
I am getting an output of
Hash Value of 14178439 : 2,3242342,2343242 3,234432,123123 2,34343
when the actual value is
Hash key :14178439 Hash Val:2,34343,
plz tell y this is happening?

Replies are listed 'Best First'.
Re: conditional exists
by JavaFan (Canon) on Jul 08, 2009 at 10:21 UTC
    @values = @{$hash{$l} || []};
    will do what you want.
Re: conditional exists
by jethro (Monsignor) on Jul 08, 2009 at 11:29 UTC

    I changed your program slightly, added strict and warnings, corrected the line where @values is set and added sample data:

    #!/usr/bin/perl use strict; use warnings; my %hash; my $l; my @values; while (<DATA>) { chomp; my ($key, $rest) = split /-/; push @{$hash{$key}},$rest; } $l=14; @values= exists $hash{$l} ? @{$hash{$l}}:undef; { print "\n Hash Value of 14 : @{$hash{$l}} \n"; } exit(0); __DATA__ 5-ax 14-vor 65-em 14-auf 14-ab

    When I run this I get the following result:

    Hash Value of 14 : vor auf ab

    which to my eye looks good. What did you expect? If you just want the first value of the array instead of the complete array printed, you could use this for example:

    if (exists $hash{$l} and @{$hash{$l}}>0) { print "Hash value of $l is $hash{$l}->[0]\n"; #or the short form $ha +sh{$l}[0] } else { print "Nothing found for $l\n"; }
      if the key exists can i get the values to an array? like
      @values= exists $hash{$l} ? @{$hash{$l}}:undef; # where @values will have vor auf ab

        Yes exactly, in my example script above @values has these values: vor auf ab

        If in doubt, just check it yourself:

        print join('|',@values),"\n"; #will print "vor|auf|ab"