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);
In reply to You can't assign $_ to a hash in a foreach statement by markdibley
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |