Reputation:
This code outputs the scalars in the row array properly:
$line = "This is my favorite test";
@row = split(/ /, $line);
print $row[0];
print $row[1];
The same code inside a foreach loop doesn't print any scalar values:
foreach $line (@lines){
@row = split(/ /, $line);
print $row[0];
print $row[1];
}
What could cause this to happen?
I am new to Perl coming from python. I need to learn Perl for my new position.
Upvotes: 2
Views: 1003
Reputation: 132811
When I run into these sorts of problems where I wonder why something in a block is not happening, I add some debugging code to ensure I actually enter the block:
print "\@lines has " . @lines . " elements to process\n";
foreach my $line ( @lines )
{
print "Processing [$line]\n";
...;
}
You can also do this in your favorite debugger by setting breakpoints and inspecting variables, but that's a bit too much work for me. :)
If you need to learn Perl and already know Python, you shouldn't have that much trouble going through Learning Perl in a couple of days.
Upvotes: 1
Reputation: 458
As already mentioned in Jefromi's comments, whatever the problem is, it exists outside of the code you posted. This works entirely fine:
$lines[0] = "This is my favorite test";
foreach $line (@lines) {
@row = split(/ /, $line);
print $row[0];
print $row[1];
}
The output is Thisis
Upvotes: 3