[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 11:43:46AM -0500, Kevin van Haaren wrote:
> At 7:43 AM -0700 1999/5/31, 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!
> >
> >Thanks for any help.
> >
> >Darryl Tang
> >
> 
> Basically it's the argument for the while statement.
> 
> It's the same as:
> 
> while (1) {
> 	do stuff;
> }
> 

Uh, no.  The 1 in the above code is the body of the while loop, not the
conditional.  (Note: 'conditional', not 'argument'.)


> 
> The construct is similar to:
> 
> do this if (this is true);
> 

Yes.  Notice where the 'this is true' occurs.


> As long as whatever you put there is true, the while statement will work.
> Eliminating it makes it undef, therefore the while is false and skips the
> statement (or it's evaluating the $number =~ construct for true/falseness,
> I'm not sure).
> 

No.  The body of the loop doesn't have to return any specific value.  The
conditional is what is being tested for truth or falseness.

undef while /foo/;

is just as valid as

1 while /foo/;


Just like
while(/foo/) { 1 }
and
while(/foo/) { undef }


If this construct tested 1 as the conditional, then it would always be true
and the loop would never terminate!


> I believe the ability to put the operation before the if/while statement
> was put there so "the important stuff" is first on the line and seen first.
> I use it a lot with the if statements, but I'm not sure it increases
> readability in a while statement (but then I'm used to the "old" style
> programming languages).

Yes.


Ronald

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