in reply to conditional exists

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"; }

Replies are listed 'Best First'.
Re^2: conditional exists
by Anonymous Monk on Jul 08, 2009 at 12:48 UTC
    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"