in reply to •Re: List assignment in scalar context
in thread List assignment in scalar context

Aha. Guess I should have RTFM. It contradicts my usually-accurate intuition about how list/scalar context works in Perl, so I hope I can be forgiven.

My real-life code that inspired this question goes something like this:

my $count = my ($arg1, $arg2, $arg3) = split /\s+/, $argstring; $count == 3 or die "3 arguments expected; you supplied $count\n";
So if I want the real argument count, I have to split into a temporary array first, or else use a dummy trailing array in the assignment list. Gross.

I can't say I care for this feature. Smells like premature optimization to me. And I notice it doesn't work across function calls. That could be a nasty surprise for someone someday.

Replies are listed 'Best First'.
Re^3: List assignment in scalar context (disable the DWIM)
by tye (Sage) on Jan 10, 2005 at 20:00 UTC
    my $count = my ($arg1, $arg2, $arg3) = split /\s+/, $argstring, -1; # ^^^^

    - tye        

Re^3: List assignment in scalar context
by demerphq (Chancellor) on Jan 10, 2005 at 19:32 UTC

    So if I want the real argument count, I have to split into a temporary array first, or else use a dummy trailing array in the assignment list. Gross.

    Personally i think the issue here is that what you are trying to do is much less common than the opposite. Ie, more people would rather have split// be faster on spliting a few elements out scenarios than they would with have it be slower but more consistant with other list returning functions. After all, split may be quite the wrong way to do this. Arguably

    my $count=()=$argstring=~/\s+/g; my ($arg1, $arg2, $arg3) = split /\s+/, $argstring;

    is better anyway, as if the $argstring is long and you only are going to store three elements then its better not do the actual splitting (creating new svs, populating them etc) when you dont need to.

    ---
    demerphq