Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Array question

by sgifford (Prior)
on Jun 14, 2008 at 03:30 UTC ( [id://692048]=note: print w/replies, xml ) Need Help??


in reply to Array question

You can add items to the end of an array with push or to the beginning with unshift. You can also add elements anywhere in the array by just storing something at the new index.

In some languages, like C and Java, you have to define the size of the array when it is created. But Perl arrays will simply grow as needed.

Replies are listed 'Best First'.
Re^2: Array question
by ww (Archbishop) on Jun 14, 2008 at 15:21 UTC

    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.

      Perhaps I was less than careful with my use of the word "add". I simply meant you can do this:
      my @arr; $arr[78] = "foo";

      But it is actually pretty straightforward to insert elements into an array, shifting all later elements, using splice:

      my @a = ('foo','baz'); splice(@a,1,0,'bar'); print "@a\n";
        ++, sgifford and many thanks!

        And, note the clarity (and, in this case, the particularity and relevance) of sgifford's explanation, as contrasted with

        perldoc -f splice splice ARRAY,OFFSET,LENGTH,LIST splice ARRAY,OFFSET,LENGTH splice ARRAY,OFFSET splice ARRAY Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. I +n list context, returns the elements removed from the array. In scalar context, returns the last element removed, or "undef" +if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everythin +g from OFFSET onward. If LENGTH is negative, removes the elemen +ts from OFFSET onward except for -LENGTH elements at the end of +the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, perl issu +es a warning, and splices at the end of the array. The following equivalences hold (assuming "$[ == 0 and $#a >= $i" ) push(@a,$x,$y) splice(@a,@a,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$i] = $y splice(@a,$i,1,$y) Example, assuming array lengths are passed before arrays: sub aeq { # compare two list values my(@a) = splice(@_,0,shift); my(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }

        For me (and for others?) the first sentence, Removes the elements designated by OFFSET and LENGTH from an array, and replaces... certainly does nothing to suggest that splice provides this elegant alternative to the overhead and verbosity of my lines 24..28 (above). Again, ++!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://692048]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-16 14:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found