Thursday, September 22, 2005

List assignment in scalar/boolean context in perl

Though this one is about perl but as i havent blogged for sometime
I'll post it here.

A collegue of mine was using a contruct like

while(my $temp = $sth->fetchrow_array)
{
# do work..

}

The problem was that whenever fetchrow_array returned 0 as
the value ,the while would exit out.

So the solution suggested by another colleague was to enclose $temp in a list
such as (my $temp)=$sth->fetchrow_array.

I was intrigued by this as a list should return the last element in scalar
context.

As it turns out
while((0)) wouldnt enter the while block but strangely.
while(($temp)=(0)) works.

This is because a list assignment in scalar context returns the number of
elements on the r.h.s of the assignment.

Yup there is more than one way to do it and one could also use
while(defined($temp=(0))) ..

1 Comments:

Anonymous Anonymous said...

dude, whats this crap u have posted? everyone knows that perl sucks

3:24 PM  

Post a Comment

<< Home