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

Hi Monks,

I recently ran in to a code:

push @comb, [$val, @$_] for combine \@rest, $n-1;

What reference is it exactly pushing in to the array with [$val, @$_]?

Please let me know if more info is needed.

Regards,
Ranjit

Replies are listed 'Best First'.
Re: Push array
by haukex (Archbishop) on Aug 08, 2016 at 12:27 UTC

    Hi reswaran,

    I'm assuming you meant push @comb, [$val, @$_] for combine \@rest, $n-1; (please use <code> tags).

    I'm not sure what combine is, but I'm going to guess that it's a function that returns a list of array references (to find out more, find out which module combine is coming from and read its documentation). For testing, I'm going to substitute the function call with a plain array.

    Then, for will loop over the elements of the list returned by combine and set $_ to each of those values. [ ... ] creates a new array reference. This new arrayref will contain the value $val, followed by the elements of the arrayref which is stored in $_ and dereferenced via @$_.

    Here, I've rewritten the for loop in a more verbose but hopefully more clear way:

    use warnings; use strict; my $val = "foo"; my @combine = (["bar","quz"],["abc","def"]); my @comb; for my $el (@combine) { push @comb, [$val, @$el]; } use Data::Dumper; print Dumper(\@comb); __END__ $VAR1 = [ [ 'foo', 'bar', 'quz' ], [ 'foo', 'abc', 'def' ] ];

    Hope this helps,
    -- Hauke D

      Thanks a lot Hauke, this helps a lot. Regards, Ranjit