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 | |
by jethro (Monsignor) on Jul 08, 2009 at 12:56 UTC |