Does split modify $_ ?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hi there,

Please see this code:

use strict;
use warnings;

open(IN, 'myfile.txt') or die "Open failed..$!\n";
while(my @arr = split /:/, <IN>)
  #print "* $_ *\n";
  if (/^#/) { print "Comment found\n"; }

I attempted to read the filename (line-by-line), split it using ':' as
seperator and stored the contents in an array. My IF check fails
despite the file having only perl comments.
$cat myfile.txt
#Simple comment
#another comment

I think that $_ is being set to undef by split.
The split documentation does not say that $_ is modified by split.

Can someone please explain why $_ is being modified here.


Re: Does split modify $_ ? writes:
Quoted text here. Click to load it

$_ is not being modified by 'split'; it's in fact never set at all.
You 'while' statement does not both iterate over the lines in the file
and over the items in the split list; it only does the former. You need
another iteration level in your code:

    while(my @arr = split /:/, <IN>) {
      for (@arr) {
        #print "* $_ *\n";
        if (/^#/) { print "Comment found\n"; }

(There may be more to say about this code - I'm new myself - but this

It's the file you want to read, by the way, not the filename.

I see that I'm assuming that your code was nearly correct already, but
do you want '#' to start a comment within each ':'-delimited field, or
only at the beginning of a line? The latter is more usual. If only at
the beginning of a line, it doesn't make sense to check for that while
iterating over the result of 'split'. I leave the necessary changes as
an exercise.

Re: Does split modify $_ ?

The <IN> in while loop will modify the $_ to contain the line read.

You can try this:
print $_;  #or simply print;

I don't understand why split sets $_ to undef...and how can I avoid
doing so?


--Posted via Google newsgroup...Sorry, folks.

Re: Does split modify $_ ?

Quoted text here. Click to load it

Did *you* try this?

A lone <$IN> does *not* set $_ to anything.  You are working on wrong
assumptions.  Read up on "while" in perlsyn to see when it does what
to $_.

Quoted text here. Click to load it

Split has nothing to do with it, $_ has never been set.


Re: Does split modify $_ ?

Kasp wrote:
Quoted text here. Click to load it

For a simple while() conditional, yes.
For a nontrivial while() conditional, no.

   while(<IN>){}    is the same as    while(defined($_=<IN>)){};
   while(something <IN>){}    is not the same; $_ is *NOT* set.

Quoted text here. Click to load it

Oh, really?  Did you actually try it?
   $_ = 'original unchanged value';
   print $_;
will not put a line of input into $_.

Quoted text here. Click to load it

If you never put anything into $_, then of course it remains undef.
You avoid this by writing code that actually puts data into $_.


Site Timeline