
Laurent_R
Veteran
/ Moderator
Feb 24, 2014, 2:27 PM
Post #3 of 4
(3894 views)
|
Re: [C_PRASANNA] Difference between the Hash retriving method via reference and Non reference
[In reply to]
|
Can't Post
|
|
If you try to run your case 1 code:
my %months = (jan => 1, feb => 2, mar => 3, apr => 4, may => 5); foreach my $mon (keys sort %months ) { #Note the below format $Value = $months->{$mon}; print "Value = $Value\n"; } it will simply not compile and give you an error message with something like this:
Type of argument to keys on reference must be unblessed hashref or arrayref... which basically means that the "arrow" notation can be used only with hashref or arrayref, not with plain hashes or plain arrays. (Another error is that you probably want 'sort keys", not "keys sort" in the foreach line. Not sure either that you really want to sort on the keys, you more probably want to sort on the values, but that's a different issue, it may be your choice to sort the months in alphabetical order if so you wish.) But if you create a hashref instead of a hash, then "arrow" notation will be useful:
my $month_ref = {jan => 1, feb => 2, mar => 3, apr => 4, may => 5}; foreach my $mon (sort keys %{$month_ref} ) { #Note the below format $Value = $month_ref->{$mon}; print "Value = $Value\n"; } although this:
$Value = $$month_ref{$mon}; will work just as well.
|