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

hi monks,

another rookie question. if i have an array initialized by:

 push @array, $someInt, $someString;

where the first entry is a number and the second is a string, how do i remove the last entry from every row in the array? that is, how do i remove the string and be left with a one column array containing only the numbers?

Replies are listed 'Best First'.
Re: removing elements from an array
by Kenosis (Priest) on Aug 09, 2012 at 16:50 UTC

    Here's another option:

    use Modern::Perl; use Data::Dumper; my @array = qw/1 A 2 B 3 C 4 D 5 E/; my $i = 0; say 'Before:'; say Dumper \@array; @array = grep !($i++ % 2), @array; say 'After:'; say Dumper \@array;

    Outout:

    Before: $VAR1 = [ '1', 'A', '2', 'B', '3', 'C', '4', 'D', '5', 'E' ]; After: $VAR1 = [ '1', '2', '3', '4', '5' ];

    This uses the modulo operator within grep to let only the even-numbered elements of the array pass.

    Hope this helps!

Re: removing elements from an array
by hbm (Hermit) on Aug 09, 2012 at 17:46 UTC

    Might your strings be numeric, or can you simply grep out non-digits?

    @array = grep !/\D/, @array;

    Otherwise, I'd grab every other like:

    my $i; @array = grep ++$i%2, @array;
Re: removing elements from an array
by Athanasius (Archbishop) on Aug 09, 2012 at 16:05 UTC

    Here is one way:

    #! perl use strict; use warnings; use Data::Dumper; my @array = (1, 'Matthew', 2, 'Mark', 3, 'Luke', 4, 'John', 5); my @copy = @array; my @list; while (@copy) { push( @list, shift @copy ); shift @copy; # throw the string away } print Dumper(\@list);

    Output:

    $VAR1 = [ 1, 2, 3, 4, 5 ];

    HTH,

    Athanasius <°(((><contra mundum

Re: removing elements from an array
by LanX (Saint) on Aug 10, 2012 at 00:45 UTC
    If the sets of integers and/or strings are unique, that is w/o repetitions AND if you don't care about the order, then better use a hash to hold the data.

    your problem could easily be solved with:

    %hash=@array; @ints = keys %hash; @strs = values %hash;

    for the second case (unique strings) use reverse

    %hash= reverse @array; @strs = keys %hash; @ints = values %hash;

    test in debugger:

    DB<103> %hash = reverse qw/1 A 2 B 3 C 4 D 5 E/ => ("E", 5, "D", 4, "C", 3, "B", 2, "A", 1) DB<104> keys %hash => ("A", "C", "D", "B", "E") DB<105> values %hash => (1, 3, 4, 2, 5)

    Cheers Rolf

Re: removing elements from an array
by Anonymous Monk on Aug 09, 2012 at 21:00 UTC
    Think of it as iterating through the existing array and creating a new array containing only what you want. Then, if you wish, empty out the old array. The approach can actually be more efficient than you suppose.