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

This is probably a dumb question. I am trying to take a list of @num_weights and add one number from @leftovers to the front, save it in a @hold_generations array, for all @leftovers. The code is:
my @num_weights = [36,264,188]; my @leftovers = [1,2,3,4]; my @hold_generations; my $i = 0; for(my $p = 0; $p < 1;$p++) #Go through all leftovers { my $pick = $leftovers[$p]; unshift @num_weights, $pick; #add item say Dumper(@num_weights); push @hold_generations, @num_weights; #store new array say Dumper(@hold_generations); splice @num_weights, 1, 1; #undo adding item say Dumper(@num_weights); }
However, I am getting this result from Dumper()
$VAR1 = [ 1, 2, 3, 4 ]; $VAR2 = [ 36, 264, 188 ]; $VAR1 = [ 1, 2, 3, 4 ]; $VAR2 = [ 36, 264, 188 ]; $VAR1 = [ 1, 2, 3, 4 ];
Shouldn't Var1 be 1,36,264,188? That's whay I'm trying to get!

I'm sure there is a better way to do this, but I'd really just like to know whats going on.

My goal is to use bigger data sets and later on check @hold_generations for specific instances and then use that instance to re-run this whole thing.

Replies are listed 'Best First'.
Re: Troubles with Unshift and Push
by vinoth.ree (Monsignor) on Mar 04, 2015 at 05:18 UTC

    Is this is correct way of creating array with three elements?, Did you try printing the values in @num_weights array?

    my @num_weights = [36,264,188]; my @leftovers = [1,2,3,4];

    All is well. I learn by answering your questions...
      Yeah, say Dumper(@num_weights)shows whats in the array.

        But it creates array with one element with anonymous array.


        All is well. I learn by answering your questions...
Re: Troubles with Unshift and Push
by ipherian (Novice) on Mar 04, 2015 at 23:49 UTC

    The bracket operator around data creates an array reference.

    my @num_weights = [36,264,188];

    At this point, @num_weights has a single scalar element, which is itself a reference to another array.

    Same as:

    my @sub_array = (36,264,188); ##real array my @num_weights = (\@sub_array); ##real array containing 1 reference

    Btw backslash is the make-reference operator



    Use parentheses to declare your arrays and it should work.

    This modified code:

    my @num_weights = (36,264,188); my @leftovers = (1,2,3,4); my @hold_generations; my $i = 0; for(my $p = 0; $p < 1;$p++) #Go through all leftovers { my $pick = $leftovers[$p]; unshift @num_weights, $pick; #add item say Dumper(@num_weights); }

    Prints:

    $VAR1 = 1; $VAR2 = 36; $VAR3 = 264; $VAR4 = 188;