http://qs1969.pair.com?node_id=726697


in reply to variable mystery

For one thing, your code doesn't run:

Can't use global $_ in "my" at /tmp/tst line 4, near "my $_ " Execution of /tmp/tst aborted due to compilation errors.

For another, all you're doing with that "map" statement is returning (via $_) the return of the substitution statement ('1') rather than the modified value of $_ - printing "@fields" would be instructive here.

Lastly, you're explicitly splitting $_ inside your loop; changing the iterator variable is thus going to leave $_ empty, which means that your code isn't going to work. Here's a slightly simpler version of your code, both with an explicit iterator and without:

#!/usr/bin/perl -w use strict; for my $foo (<DATA>) { my @fields = grep { s/^\s+|\s+$//g; 1; } split /\|/, $foo; print "$fields[1]\n"; } __END__ Baw|Vao|111 Noa St||NewYork|NY|10012|2123456789|123456789 Vca|Wxr|384 Mkl Ln|Xillo|Crrnt Stt|CT|05506|1015567781|1015567782 Uaa|Kvbr|805 Test Rd|Zero|This St|MN|17205|3018757203|3012986736 Caa|Lvbr|905 Test Rd|Bero|That St|MD|12705|3028887203|3028886736 Eaa|Pvbr|311 Zest Rd|Tero|My St|MI|12505|3018757203|3012986736
#!/usr/bin/perl -w use strict; for (<DATA>) { my @fields = grep { s/^\s+|\s+$//g; 1; } split /\|/; print "$fields[1]\n"; } __END__ Baw|Vao|111 Noa St||NewYork|NY|10012|2123456789|123456789 Vca|Wxr|384 Mkl Ln|Xillo|Crrnt Stt|CT|05506|1015567781|1015567782 Uaa|Kvbr|805 Test Rd|Zero|This St|MN|17205|3018757203|3012986736 Caa|Lvbr|905 Test Rd|Bero|That St|MD|12705|3028887203|3028886736 Eaa|Pvbr|311 Zest Rd|Tero|My St|MI|12505|3018757203|3012986736

The output in both cases is:

Vao Wxr Kvbr Lvbr Pvbr

Update: I just noticed one more thing: you're using "\r" when you're printing - which means that you're going to overwrite every line that you print. This means that you'll only see the last line, plus anything left over (i.e., anything that was past the current last character) from the previous lines. The correct character to use, at leat in the Unix world, is "\n"; for DOS-based systems, "\n\r" is appropriate.


--
"Language shapes the way we think, and determines what we can think about."
-- B. L. Whorf