Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Converting array reference to list context

by pavunkumar (Scribe)
on Dec 31, 2010 at 05:02 UTC ( #879903=perlquestion: print w/ replies, xml ) Need Help??
pavunkumar has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
$arr_ref = ( [ 1,2,3 ] ) ; @array = @$arr_ref ; #Now, @array has those three elements . @arr_ref_new = ( [1],[2],[3,4] ) ;
Like, above I want to assign these elements into one @new_array. Is there any way to achieve in one line(step)


Thanks

Comment on Converting array reference to list context
Download Code
Re: Converting array reference to list context
by Anonymous Monk on Dec 31, 2010 at 06:00 UTC
    Since your $arr_ref_new has elements in it that $arr_ref didn't, I don't know what you want to do. but maybe this would help:
    my $foo = [1,2,3]; # assign (1,2,3) to @bar my @bar = @$foo; # assign ([1],[2],[3]) to @baz my @baz = map { [$_] } @$foo;
Re: Converting array reference to list context
by ikegami (Pope) on Dec 31, 2010 at 06:10 UTC

    First, "$arr_ref_new = ( [1],[2],[3,4] );" can't possibly be what you want. You construct three arrays then proceed to discard two. (Why didn't you ask why you were getting "in void context" warnings?) So you're not clear on the inputs to your problem.

    Second, you're not very clear on what output you want either.

    I think you want:

    my $aoa = [ [1],[2],[3,4] ]; my @flat = map { @$_ } @$aoa; # @flat = (1,2,3,4)

    Update: Fixed variable name mismatch.

Re: Converting array reference to list context
by AnomalousMonk (Monsignor) on Dec 31, 2010 at 19:16 UTC

    Insofar as I understand the (apparently edited) OP, a recursive approach also works (and is almost one line):

    >perl -wMstrict -le "my @a_refs = ([1], 2, [3, 4], [5, [6, [7, 8]]], 9); ;; sub flatten { map { 'ARRAY' eq ref() ? flatten(@$_) : $_ } @_ } ;; my @flattened = flatten(@a_refs); use Data::Dumper; print Dumper \@flattened; " $VAR1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];

    Note: This also works on the original example (Update (per GrandFather): as it was ultimately updated:)  ([1],[2],[3,4]) array.

      The last line of the original code was:

      $arr_ref_new = ( [1],[2],[3,4] ) ;
      True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://879903]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (16)
As of 2014-07-30 17:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (237 votes), past polls