in reply to Re: insert element into an array
in thread insert element into an array

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; }

Replies are listed 'Best First'.
Re^3: insert element into an array
by davorg (Chancellor) on Nov 18, 2004 at 15:24 UTC

    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