http://www.perlmonks.org?node_id=11133577


in reply to Re^4: $_ not set in while <>
in thread $_ not set in while <>

G'day Marshall,

I think the issue here is that the OP wrote "read a file", not "read from the keyboard". If the sentinel value is detected, then processing of the file should stop; however, I think it's reasonable to assume that if no sentinel value is detected, then processing of the file should stop at the end of the file.

Note that in the examples below, I used a common alias of mine:

$ alias perle alias perle='perl -Mstrict -Mwarnings -Mautodie=:all -MCarp::Always -E +'

Here's a file that simulates your keyboard input. I've added an extra line that is to be ignored:

$ cat > pm_11133571.dat 234 asdf quit ignore

That is processed (almost) identically to your keyboard input:

ken@titan ~/tmp $ perle 'my $line; while ( (print "list of letters: "),$line=<>, $line + !~ /\s*quit|exit|q\s*$/i) { print "doing something with $line\n"}' p +m_11133571.dat list of letters: doing something with 234 list of letters: doing something with asdf list of letters: ken@titan ~/tmp

I said "almost" because, as you may have noticed, there's a dangling "list of letters: " prompt as the last line of output.

However, if there's no sentinel value, processing does not stop at the end of the file; instead, the code is stuck in a loop. Also, warnings are emitted. Both of those things are what ++ikegami predicted.

Consider this slightly different input file (without a sentinel):

$ cat > pm_11133571_2.dat 234 asdf ignore

Here's what happens:

$ perle 'my $line; while ( (print "list of letters: "),$line=<>, $line + !~ /\s*quit|exit|q\s*$/i) { print "doing something with $line\n"}' p +m_11133571_2.dat list of letters: doing something with 234 list of letters: doing something with asdf list of letters: doing something with ignore Use of uninitialized value $line in pattern match (m//) at -e line 1, +<> line 3. at -e line 1, <ARGV> line 3. Use of uninitialized value $line in concatenation (.) or string at -e +line 1, <> line 3. at -e line 1, <ARGV> line 3. list of letters: doing something with list of letters:

The screen output stopped there; I used Ctrl-C to get back to my shell prompt. Of course, I could've typed one of the sentinel values (quit|exit|q) but would you expect users to know what those values were; and even if they did, would you expect them to do this in the "production" environment you described.

Update: I started to compose my response before your post had any updates. After posting, I see you've added three updates. That's not a complaint about the updates; just advice on what I was responding to.

— Ken