http://qs321.pair.com?node_id=692082


in reply to Re: Array question
in thread Array question

This is either "picky" or "iggerant" but the statement (above) that...

"You can also add elements anywhere in the array by just storing something at the new index."

... seems to me to be, at once, true, and "possibly confusing."

In short, I don't know any function that will add an element to an array at any arbitrary index nor any technique (aside from the one below) for doing so.

#!usr/perl/bin use strict; use warnings; use Data::Dumper; my $file0 = "foo.txt"; my $file1 = "bar.txt"; my $file2 = "blivitz.txt"; my @array1 = ($file0, $file1, $file2); print "Initial array:\n"; my $elementindex = 0; for my $file(@array1) { print "\$elementindex $elementindex is $file\n"; $elementindex++; } print "\n"; # Now adding an interior element to the array, in this case, arbitrari +ly inserting "new element" # after "foo.txt" and before "bar.txt" #(to add to beginning or end, see push and unshift) my @temp_array = @array1; # copy all elements to new array @temp_array = ($array1[0], "new element", $array1[1], $array1[2]); @array1 = @temp_array; # copy revisions back to @array1 $elementindex = 0; for my $file(@array1) { print "After revisions, \$elementindex $elementindex is $file\n"; $elementindex++; } print "\n"; # This REPLACES the latest content of $array1[1], "new element", with +$addelement.txt # BUT note it's NOT "add"(ing) an element "anywhere" my $addelement = "addelement.txt"; $array1[1] = $addelement; # $elementindex = 0; for my $file(@array1) { print "now \$elementindex $elementindex is $file\n"; $elementindex++; }

Output:

$elementindex 0 is foo.txt $elementindex 1 is bar.txt $elementindex 2 is blivitz.txt After revisions, $elementindex 0 is foo.txt After revisions, $elementindex 1 is new element After revisions, $elementindex 2 is bar.txt After revisions, $elementindex 3 is blivitz.txt now $elementindex 0 is foo.txt now $elementindex 1 is addelement.txt now $elementindex 2 is bar.txt now $elementindex 3 is blivitz.txt

Perhaps splice() ( perldoc -f splice ) is also an option but thus far /me does not see how to implement it.