SPUG: itm 60 in effective perl programming

John W. Krahn krahnj at telus.net
Thu Feb 24 12:44:18 PST 2005

Tim Maher wrote:
> On Thu, Feb 24, 2005 at 01:53:45AM -0800, John W. Krahn wrote:
>>>-- it's like the UNIX shell's "read"
>>>command, except it loads $_ with the next line of input
>>>rather than some other variable.  
>>IIF it is used in a while loop conditional!
> Not IIF, because in addition to the while case it also loads $_ for
> 	for ($i; <>; $i++)

I didn't mention the C style for loop because as any C or Perl programmer
should know it is equivalent to a while loop.  (See K&R 2nd ed. section 3.5
and the "For Loops" section of perlsyn.pod.)

> and in the absence of some other specified loop variable, also for 
> 	"foreach (<>)" 

In a foreach loop the expression is expanded to a list and the loop variable
is an *alias* to each member of that list in turn.  This is usually very
inefficient for reading from a file as the whole file has to exist in memory.

> and of course, it also loads $_ when the implicit loop of -n/-p
> is used. 

Because -n and -p use a while loop.

$ perl -MO=Deparse -ne1
LINE: while (defined($_ = <ARGV>)) {
-e syntax OK

>>>But IMHO, that's a pretty inscrutable way to join lines.  Here's a more
>>>"scrutable" way, based on the implicit loop (-p), assuming you really
>>>want a space between each pair of lines as shown above:
>>>perl -wpe 's/\n$/ /;' file	# replace newline with space
>>Also, the end of line anchor ($) is superfluous as there is
>>only one newline in every line (unless you change the Input
>>Record Separator.)
> Yes, but IMHO it's often worth adding a "superfluous" character or two to
> make a program more readable -- and the original poster was a confused
> newbie, after all, so I was going for "added scrutability" 8-}

Yes, "more readable" is a laudable goal.  Since $ can match before or after
the last newline does /\n$/ match the last newline or the second-last newline?
Perhaps you meant to use the end of string anchor \z instead?   :-)

use Perl;

More information about the spug-list mailing list