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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: variable mystery
by ikegami (Patriarch) on Nov 29, 2008 at 02:59 UTC | |
Re^2: variable mystery
by jeah (Novice) on Nov 29, 2008 at 05:27 UTC | |
by Anonymous Monk on Nov 29, 2008 at 05:37 UTC | |
by jeah (Novice) on Nov 29, 2008 at 07:21 UTC | |
by parv (Parson) on Nov 29, 2008 at 07:59 UTC | |
by ikegami (Patriarch) on Nov 29, 2008 at 12:44 UTC | |
by jeah (Novice) on Nov 30, 2008 at 02:29 UTC | |
Re^2: variable mystery
by CountZero (Bishop) on Nov 29, 2008 at 08:10 UTC | |
by pobocks (Chaplain) on Nov 29, 2008 at 10:37 UTC | |
Re^2: variable mystery
by ikegami (Patriarch) on Nov 29, 2008 at 12:50 UTC | |
Re^2: variable mystery
by mandarin (Hermit) on Nov 29, 2008 at 12:52 UTC |