tags:

views:

129

answers:

3

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.

A: 

Appearently I needed to do:

foreach $line (@lines){
   @row = split(/\s+/, $line);
   print $row[0];
   print $row[1];
}
foxhop
I don't buy this. Yes, your first split was probably bad since it split on single spaces, so ` a b` would turn to `("", "", "", "a", "", "b")`, but given the same input, the code will do the same thing in the two places.
Jefromi
+3  A: 

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

cikkle
A: 

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.

brian d foy