SPUG: while question

Yitzchak Scott-Thoennes sthoenna at efn.org
Tue Sep 16 14:26:30 CDT 2003


The two forms:
  $foo = $obj->method()
  ($foo) = $obj->method()
can have quite different results.

Saying $foo = $obj->method() will call it in scalar context while
($foo) = $obj->method() will call it in list context and assign the
first item returned to $foo.

Some implications are:

If method() is always returning an explicit list or slice, $foo =
$obj->method() will give $foo the *last* item in the list, while
($foo) = $obj->method() will give $foo the *first* item.  If method()
is returning an array or hash, the assignment with parens will give
$foo the first element or key.  Without parens, it will give a count
of elements for an array.  For a non-tied hash, $foo will be false if
the hash is empty and (true) bucket usage otherwise.  For a tied hash,
the returned value will be meaningless and probably false.

Saying "defined $foo = $obj->method()" doesn't work because defined
is a unary operator with higher precedence than =.  You would say
defined( $foo = $obj->method()) instead.

On Tue, Sep 16, 2003 at 11:37:32AM -0700, Peter Darley <pdarley at kinesis-cem.com> wrote:
> Adrian,
> 	That is exactly what I was looking for!
> Thanks,
> Peter Darley
> 
> -----Original Message-----
> From: spug-list-bounces at mail.pm.org
> [mailto:spug-list-bounces at mail.pm.org]On Behalf Of Adrian Hands
> Sent: Tuesday, September 16, 2003 11:25 AM
> To: spug-list at mail.pm.org
> Subject: Re: SPUG: while question
> 
> 
> The real problem here is fetchrow() returns a list and you're assigning it
> to a scalar.
> Simply add some parens and your while loop will no longer incorrectly break
> on zero.
> I.e.:
> 
>  while ( ( $MyData ) = $sth->fetchrow() )



More information about the spug-list mailing list