Perl: Passing by reference does not modify the hash -


my understanding in perl pass hashes functions reference

consider following example, modify hash in modifyhash function

#!/usr/local/bin/perl  %hash;  $hash{"a"} = "1"; $hash{"b"} = "2";   print (keys %hash); print "\n";  modifyhash(\%hash);  print (keys %hash); print "\n";  sub modifyhash {     $hashref = @_[0];     %myhash = %$hashref;     $myhash{"c"} = "3";     print (keys %myhash);     print "\n"; } 

the output of script is:

ab abc ab 

i have expected be:

ab abc abc 

...as pass hash reference.

what concept missing here passing hashes functions?

that's because when my %myhash = %$hashref;, you're taking copy of dereferenced $hashref , putting %myhash same thing my %myhash = %hash;, you're not working on referenced hash @ all.

to work on hash specified reference, try this...

sub modifyhash {     $hashref = $_[0];     $hashref->{"c"} = "3";     print (keys %$hashref);     print "\n"; } 

as pointed out thissuitisblacknot in comments below, @_[0] better written $_[0]. should using use strict; , use warnings;, have been caught. because you're sending in reference, have used my $hashref = shift;.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -