in reply to insert element into an array

You're splicing onto the wrong array.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @R = ([qw(x y z)], [qw(a b c)], [qw(e f g)], [qw(h i j)]); print Dumper \@R; 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" } } print Dumper \@R;

splice @$rc instead of splice @R.

--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: insert element into an array
by Anonymous Monk on Nov 18, 2004 at 12:49 UTC
    I obviously have a lot to learn about about the wonders of splice with arrays.
    If using your example I wanted to delete the row instead of insert a new element, how would I do it ?
    I tried
    for my $rc (@R) { if ($rc->[0] eq "a") { splice @$rc, 0, 2; } }
    but this just removes everything (including the line I want to delete) up to the end of the array
    I also tried this
    for my $rc (@R) { if ($rc->[0] eq "a") { delete $rc->[0-2]; } }
    This works but then when I try to print the array out I get an uninitialized value in concatenation error.
    I'd expected this because the array wasn't scrunched up and delete is not the right thing to use I guess. The print I used was
    foreach (@records) { $buf .= "$_->[0] $_->[1] $_->[2] $_->[3]\n"; print $buf; }

      Once again you're splicing the wrong array :) If you want to remove a row, then you want to alter the outer array, @R.

      But in this case, splice is really the wrong tool. Here you probably want to use grep.

      #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @R = ([qw(x y z)], [qw(a b c)], [qw(e f g)], [qw(h i j)]); print Dumper \@R; @R = grep { $_->[0] ne 'a' } @R; print Dumper \@R;
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        Many thanks for your reply