rovf has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monk Fellows:
Is it possible to do the following without reverting to a temporary variable?

# split a string and put the pieces into an array and # assign the reference to this array to $aref my @temporary=split(/\D+/,"1,2xx4:17"); $aref=\@temporary # [1,2,4,17]

I thought about putting split into array context with something like ()=split(...), but this would also empty my array...

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: split and assign to arrayref in one go?
by moritz (Cardinal) on Jun 16, 2008 at 14:33 UTC
    You need [...] for creating array refs:
    my $aref = [ split(/\D+/,"1,2xx4:17") ];

    See perlreftut, perlref and References Quick Reference for details. (Update: I just noticed the latter is about dereferencing, not about creating anonymous data structures. Might be helpful nonetheless).

      Oh my! I think it's time to go home, if I couldn't have seen it by myself. Probably I'm working too long already. Thanks a lot for your solution!
      -- 
      Ronald Fischer <ynnor@mm.st>
Re: split and assign to arrayref in one go?
by radiantmatrix (Parson) on Jun 16, 2008 at 15:58 UTC

    An alternative to moritz's solution, you could do this:

    @{ $aref } = split(/\D+/,"1,2xxx4:17");

    It says "store the result of the split into the array referenced by $aref". If $aref is undefined or an ArrayRef already, this works, even with strict and warnings.

    $ perl -w -Mstrict -MData::Dumper -e 'my $x; @{$x} = split /\s/, "the +one true"; print Dumper($x)' $VAR1 = [ 'the', 'one', 'true' ];

    If $aref is a different kind of reference, then you will get a fatal "Not an ARRAY reference".

    $ perl -w -Mstrict -MData::Dumper -e 'my $x = {}; @{$x} = split /\s/, +"the one true"; print Dumper($x)' Not an ARRAY reference at -e line 1.
    <radiant.matrix>
    Ramblings and references
    “A positive attitude may not solve all your problems, but it will annoy enough people to make it worth the effort.” — Herm Albright
    I haven't found a problem yet that can't be solved by a well-placed trebuchet
      Autovivification if $aref hasn't been defined yet - this is also an elegant solution!!! I already went with moritz's idea, but will keep yours in mind for the next occasion.
      -- 
      Ronald Fischer <ynnor@mm.st>