in reply to Conditional initialisation

Wow. Thanks. The first two replies cleared up a few related uncertainties that were lurking in the background for me.

But the particular problem you cited is not actually something I would have run into myself, because I've never used that sort of idiom in a subroutine. So I'm curious... what's the motivation for doing this:

my @list; @list = @_ if ( @_ > 0 ); # (using the "safe" form) # when no args have been passed, @list is empty (undef) at this point. +..
as opposed to doing this (which is what I always do, and I thought everybody always did it pretty much this way):
my @list = @_; # when no args have been passed, @list is empty (undef) at this point. +..
If there's a difference between those two, I'm having trouble seeing it. (Well, okay, with the former, one can easily fall into the trap that you described, but besides that, what's the difference?)

Replies are listed 'Best First'.
Re: Re: Conditional initialisation
by Akhasha (Scribe) on May 25, 2004 at 01:44 UTC

    Ah, well the last time I used this construct it was for a function that could accept either a unix timestamp as a scalar, or a time vector as returned by localtime() or gmtime().

    So I was checking the length of @_ to see if it was greater than 1 (not 0), like this:

    sub unix_to_datetime { my @time_vec; @time_vec = @_ if @_>1; unless (@time_vec) { my $time = shift; @time_vec = (defined $time ? localtime($time) : localtime); } return strftime('%Y-%m-%d %H:%M:%S', @time_vec); }
      Wouldn't the following work just the same?
      sub foo { my @time_vec = @_ > 1 ? @_ : defined $_[0] ? localtime($_[0]) : localtime; return strftime('%Y-%m-%d %H:%M:%S', @time_vec); }

      ------
      We are the carpenters and bricklayers of the Information Age.

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      I shouldn't have to say this, but any code, unless otherwise stated, is untested