prbndr has asked for the wisdom of the Perl Monks concerning the following question:

hi monks, my question should be relatively simple, but as i am a perl newbie, it is a little difficult for me to find a way to do this: i have a 2D array (initialized with push @positions, $read->start - 1, $base;). column 1 is full of scalars and column 2 is a corresponding string. e.g. array = {1, A; 2, A; 3 G; 4 T; 5 C}. if the second column of a row starts with a G or a C, i would like to remove it. how do i go about doing this? i heard something about the splice function, so maybe that can point me in the right direction. thanks!

Replies are listed 'Best First'.
Re: removing rows from an array
by toolic (Bishop) on Aug 08, 2012 at 15:34 UTC
    grep is one way:
    use warnings; use strict; use Data::Dumper; my @positions = ( [qw(1 A)], [qw(2 A)], [qw(3 G)], [qw(4 T)], [qw(5 C)], ); @positions = grep { (@{ $_ })[1] !~ /^[GC]/ } @positions; print Dumper(\@positions); __END__ $VAR1 = [ [ '1', 'A' ], [ '2', 'A' ], [ '4', 'T' ] ];

    See also:

    UPDATE: Seeing aitap's solution reminds me of simpler syntax:

    @positions = grep { $_->[1] !~ /^[GC]/ } @positions;
Re: removing rows from an array
by stonecolddevin (Parson) on Aug 08, 2012 at 15:37 UTC

    I like to use Set::Scalar for this sort of stuff.

    Three thousand years of beautiful tradition, from Moses to Sandy Koufax, you're god damn right I'm living in the fucking past

Re: removing rows from an array
by tobyink (Canon) on Aug 08, 2012 at 15:38 UTC
    # Here's the alphabet. my @alphabet = 'A'..'Z'; # Remove 22 elements from @alphabet, starting at $alphabet[2]. splice(@alphabet, 2, 22); # Now my dictionary-authoring project will take much less time! print "$_\n" for @alphabet;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: removing rows from an array
by aitap (Curate) on Aug 08, 2012 at 15:45 UTC

    First of all, can you please properly format your message?

    i have a 2D array (initialized with push @positions, $read->start - 1, $base;).
    Actually, you have only 1D array. Read perlreftut to know how to make "2D-arrays" (they are called arrays of arrays there) properly.

    Apart from grep (described above) you can use map to go through your array and remove unnecessary elements. For example, map { $_->[1] eq 'G' && () } @array

    Sorry if my advice was wrong.