What the user want to do is use the $hash{key} as the string receiptor of the foreach, something like that:
But this code can't be compiled since foreach only accept a scalar to receive the array string. Thinking in that I made a code that use a scalar variable that has a direct access to the value of the key in the hash:foreach $hash{key} (@array){ ## The value of $hash{key} will be the $array[x] value. ## ... }
Soo now I have a scalar variable that I can read and write to it and affect the value of the key in the hash (a scalar linked to the value of the key). Now I tried to use the same scalar in the foreach:my %hash = ( key => 'value'); my $k_ref = \$hash{key} ; *{'main::val'} = $k_ref ; ## To avoid $$k_ref print "val: <$val>\n" ; print "key: <$hash{key}>\n" ; $val = 'test' ; print "val: <$val>\n" ; print "key: <$hash{key}>\n" ;
But running the code you can see that it doesn't work like you want. The output inside the foreach will be:my %hash = ( key => 'value'); my $k_ref = \$hash{key} ; *{'main::val'} = $k_ref ; my @array = (0..5) ; print "val: <$val>\n" ; print "key: <$hash{key}>\n" ; foreach $val ( @array ) { print "for>> val: <$val>\n" ; print "for>> key: <$hash{key}>\n" ; } print "val: <$val>\n" ; print "key: <$hash{key}>\n" ;
And not:for>> val: <0> for>> key: <value> for>> val: <1> for>> key: <value> for>> val: <2> for>> key: <value> ...
Why this hapens?! Because when you put a $scalar in the foreach to reaceive the string, you are accessing the scalar inside the array directly, and not copying the content to the scalar! This is why when you change the value of the scalar the array is changed too:for>> val: <0> for>> key: <0> for>> val: <1> for>> key: <1> for>> val: <2> for>> key: <2> ...
And this is a good thing, since is a speed improvement too. I know that the idea to affect the value of a key with the foreach is not a code that is useful, since you can make it explicit:my @array = (1..5) ; print "@array\n" ; foreach my $array_i ( @array ) { $array_i *= 10 ;} print "@array\n" ;
But you can see that Perl is very powerful, specially with variables. only using other languages to see that... ;-Pmy %hash = ( key => 'value'); my @array = (0..5) ; foreach my $val ( @array ) { $hash{key} = $val ; print "for>> val: <$val>\n" ; print "for>> key: <$hash{key}>\n" ; }
Graciliano M. P.
"The creativity is the expression of the liberty".
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Foreach & scalar ref: break of way that it is suposed to work! (local)
by tye (Sage) on Apr 08, 2003 at 20:09 UTC | |
|
Re: Foreach & scalar ref: break of way that it is suposed to work!
by shotgunefx (Parson) on Apr 08, 2003 at 20:08 UTC | |
|
Re: Foreach & scalar ref: break of way that it is suposed to work!
by Juerd (Abbot) on Apr 08, 2003 at 22:41 UTC | |
by dragonchild (Archbishop) on Apr 08, 2003 at 22:53 UTC | |
by Juerd (Abbot) on Apr 08, 2003 at 23:10 UTC |