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

Re: [FWP] Fun with lvalue subs



sthoenna@efn.org (Yitzchak Scott-Thoennes) writes:

> In article <m13dkhukfy.fsf@rt158.private.realtime.co.uk>,
> Piers Cawley <pdcawley@bofh.org.uk> wrote:
> > 
> > sub my_substr ( $$;$$ ) : lvalue {
> >     my $retval;
> >     tie $retval, 'Lval', \ $_[0], @_[1,2] or die;
> >     $retval = $_[3] if exists $_[3];
> 
> Thats a cute way of checking if a parameter was passed, but doesn't
> work in all cases.  Internally, exists on an array element (a new
> feature with 5.6.0, for those who are wondering) just checks if the
> scalar value pointer is to the special global undef value.  Thus it
> will not always work, since sometimes an undef value that is pass in
> will also actually be the global undef value.  For instance:
> 
> #!perl -w
> sub e
> { 
>     print(scalar @_, " parameter(s) passed.  Parameter 0 ",
>           exists $_[0] ?  "exists!\n" : "Doesn't exist!\n")
> }
> e(undef);  # a value passed but exists is false
> e($_) for undef;  # also through an alias
> sub ee { e(@_) }
> ee(undef);        # including an alias through @_
> 
> The moral: if you want to check if a parameter is defined, use
> defined().  If you want to check if a parameter was passed, use
> scalar(@_).

Damn. And it seemed such a good idea at the time. Shame.

-- 
Piers


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe