|Perl Monk, Perl Meditation|
Re: reading array elementsby jonadab (Parson)
|on Dec 17, 2008 at 12:58 UTC||Need Help??|
Hi, sorry it took me so long to get back to you on this; I had a couple of busy weeks and didn't look at Perlmonks. But anyway, in case you're still interested, I'll go ahead and answer now...
If I use $in on Lines 6 - 8 and print any elements, the entire lines of the file are returned without being processed (with pipes included). I thought I could substitute $_ with any variable. Why won't it work here?
$_ is magic, and sometimes refers to different things according to context. In particular, map assigns each of the things in the list to $_ in turn and uses the codeblock to transform them, so when you use $_ inside a map codeblock, it refers to one item in the list that you are mapping over. You can and should use a different variable outside the map (and, indeed, the code as you have it now won't compile because you tried to scope $_ lexically; changing it to $in fixes this), but inside the map codeblock the $_ has special meaning, and you need it there.
If I UnComment Lines 9 - 11, a '1' is returned between the last 2 elements in each line. Why is that?
Because one substitution was made. The substitution operator (s///) returns undef when there were no substitutions made, but otherwise it returns the number of substitutions performed. If you don't understand why the return value of the substitution operation is appearing in your output, you should maybe look at the syntax in your map operation more closely. You're returning a list of two things for each one thing in the input list. (If this is not what you want, you can return only the last item by changing the comma to a semicolon.)
even-numbered elements return nothing
If you change your data so that they include more trailing spaces, you'll get numbers there instead of nothing. But if you don't want those values at all, you can change the map operation as mentioned above.
We're working on a six-year set of freely redistributable Vacation Bible School materials.