markdibley has asked for the wisdom of the Perl Monks concerning the following question:
I have tried everything I can think of (plus a tonne of random experiments) to assign $_ within the foreach statement to a hash. I know that you can assign it after the foreach line, but I have a very particular code limitation which doesn't allow me to do this.
#!/usr/bin/perl -s use strict; use Data::Dumper; my @x = qw(a c e g); my $var = {'a'=>"z", 'b'=>"y", 'c'=>"x", 'd'=>"w", 'e'=>"v", 'f'=>"u", + 'g'=>"t", 'h'=>"s"}; my $y = "e"; foreach $var->{$y} (@x){ print "$y = $var->{$y}\n"; $y = $var->{$y}; } die Dumper($var);
What I think is happening is the perl compiler cannot handle '{' and '}' characters in the position where it is looking for $VAR to assign $_ to. When I run the code not only do I get an error about the foreach line, but I also get a syntax error about the print line where there is no syntax error.
syntax error at ./foreach2var.pl line 9, near "$var->" syntax error at ./foreach2var.pl line 12, near "}" Execution of ./foreach2var.pl aborted due to compilation errors.
Is there any way to assign $_ within the foreach statement directly to a hash reference rather than assigning it with $var->{$y} = $_; on the following line?
I am looking for the following output
e = a a = c c = e e = g $VAR1 = { 'e' => 'g', 'a' => 'c', 'd' => 'w', 'c' => 'e', 'h' => 's', 'b' => 'y', 'g' => 't', 'f' => 'u' };
Also, I am aware that the following works, but again, I have a particular code limitation which means I have to be able to handle foreach statements
#!/usr/bin/perl -s use strict; use Data::Dumper; my @x = qw(a c e g); my $var = {'a'=>"z", 'b'=>"y", 'c'=>"x", 'd'=>"w", 'e'=>"v", 'f'=>"u", + 'g'=>"t", 'h'=>"s"}; my $y = "e"; while($var->{$y} = shift @x){ print "$y = $var->{$y}\n"; $y = $var->{$y}; } die Dumper($var);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: You can't assign $_ to a hash in a foreach statement
by ikegami (Patriarch) on Apr 08, 2022 at 16:49 UTC | |
by markdibley (Sexton) on Apr 08, 2022 at 17:03 UTC | |
by ikegami (Patriarch) on Apr 08, 2022 at 17:09 UTC | |
|
Re: You can't assign $_ to a hash in a foreach statement
by cavac (Prior) on Apr 11, 2022 at 07:01 UTC | |
|
Re: You can't assign $_ to a hash in a foreach statement
by k-mx (Scribe) on Apr 15, 2022 at 11:24 UTC | |
|
Re: You can't assign $_ to a hash in a foreach statement
by Anonymous Monk on Apr 08, 2022 at 19:11 UTC |