[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Commify and "1 while" syntax



On Mon, May 31, 1999 at 07:43:24AM -0700, Darryl Tang wrote:
> Hi everyone,
> 
> I was racking my brain last night over this one:
> 
> 	1 while ($number =~ s/^(-?\d+)(\d{3})/$1,$2/);
> 
> This will add commas into a number string and is similar to the example in
> the Programming Perl book (2d Edition) on page 74.  I understand that the
> "1 while" will make Perl repeatedly match the regular expression and apply
> it to $number, resulting in commas in the appropriate spots.
> 
> My question is what is the "1" preceding "while" for?  You can change the
> "1" to something else (e.g. "2", or "FOO" or "x") and it still works
> properly, but you can't eliminate it entirely.  I can't find any
> explanation as to what this string preceding the while is supposed to do.
> I can take it on faith that this is appropriate syntax, but I like to
> understand what is going on!
> 

This is the statement modifier form of while.  while is modifying the
statement '1'.  This is just another way of writing:

while ($number =~ s/^(-?\d+)(\d{3})/$1,$2/) {
    1;
}

In the same way that you can't leave out the 1 in the first case, you can't
leave out the { 1; } in the second case.  Even though it isn't doing
anything at all.


Here's an example where the statement actually does something useful:

print while (<>);


HTH!


Ronald

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org