in reply to Idiomatic Split to Scalar Conversion


Perlfunc on split says that "If not in list context ... splits into the @_ array". So I guess that the warning is valid.

If you are just counting you could do:     my $foo = $bar =~ tr/,/,/ + 1; To stick with split you could do this:

my $foo = my @a = split /,/, $bar; # Or this $foo++ for split /,/, $bar; # But why doesn't this work? my $foo = () = split /,/, $bar;

--
John.

Replies are listed 'Best First'.
Re: Re: Idiomatic Split to Scalar Conversion
by sfink (Deacon) on Apr 30, 2002 at 00:11 UTC
    > # But why doesn't this work? > my $foo = () = split /,/, $bar;

    Because split is DWIM-happy (or DWYTIM -- Do What You Think I Mean), and it's told the length of the array it is assigning into so it can stop looking after it fills your array.

    my $foo = () = split(/,/, $bar, -1) almost works, but it doesn't strip trailing undefs like it would in list context without the third param (try it with "a,b,,").

    If you don't mind wiping out @_, then just be explicit about it:

    my $foo = @_ = split /,/, $bar

      interestingly enough,

      my $foo = @{[]} = split( /,/, $bar );
      seems to work ( and this one's strict- and warnings-happy :-)

      ~Particle *accelerates*