in reply to insert element into an array

The problem is that you're splicing the main array, not the nested array, so everything after the found line gets pushed forward one, and the line gets found again endlessly. A better piece of code would be:
use strict; use warnings; my @R; # Constructing your matrix... while (<DATA>) { chomp; push @R, [split(/ /)]; } for (@R) { if ($_->[0] eq 'a') { unshift @$_, '#'; print join("\t", @$_)."\n"; } } __DATA__ x y z a b c e f g h i j
EDIT: And here's your code, modified so it works. I'd personally use unshift rather than splice, though...
for my $rc(@R) { if ($rc->[0] eq "a") { splice @$rc, 0, 0, '#'; print "$rc->[0]\t","$rc->[1]\t","$rc->[2]\t","$rc->[3] +\n"; } }
You were missing a > and a ; on line 4, btw.

Replies are listed 'Best First'.
Re^2: insert element into an array
by Anonymous Monk on Nov 16, 2004 at 14:41 UTC
    Thanks for your (and Dave's) answer.
    You mention you'd rather use unshift, is this for any particular reason (like performance maybe) ?
    As a newbie to Perl I'd like to understand which is the preferred method. Or is it just down to personal choice ?
    In this particular case I wouldn't expect the matrix to be more than about 100 records by the way.

      Something leads me to believe performance is the same with both (but Benchmark if you want to be sure). The reason would be readability. splice(@a, 0, 0, $val); is not even closely as readable as unshift(@$rc, $val);.

      By the way, Perl is very efficient at adding to and removing from both the front and the end of arrays. That includes shift, unshift, push, pop, their splice equivalents, and probably $a[@a] = $val.