Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

ignoring the first element of an array

by Anonymous Monk
on Feb 03, 2003 at 12:26 UTC ( [id://232200] : perlquestion . print w/replies, xml ) Need Help??

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

Hi monks, I am iterating over an array and doing something with each element. But i want to ignore the first element and can't think how to do this?? How can I ignore $derivative[0] ??
foreach my $well (@derivative) { # blah blah blah }

Edit: Added <code> tags. larsen

Replies are listed 'Best First'.
Re: ignoring the first element of an array
by jmcnamara (Monsignor) on Feb 03, 2003 at 12:39 UTC

    Here are three possible ways:
    # Use a sentinel variable my $first; foreach my $well (@derivative) { next unless $first++; # Do something } # Use an array slice foreach my $well (@derivative[1..$#derivative]) { # Do something } # Use the array indices foreach my $i (1..$#derivative) { my $well = $derivative[$i]; # Do something }

    --
    John.

      The fourth way! (sounds like a book title:)

      my $tmp = shift@derivative; for my $well (@derivative) { # } unshift @derivative, $tmp;

        The destructive way...

        for my $well (splice @derivative, 1, @derivative) { # }

        Cheers,

        -- Dave :-)


        $q=[split+qr,,,q,~swmi,.$,],+s.$.Em~w^,,.,s,.,$&&$$q[pos],eg,print
        or the destructive and funky version of your code ;-)
        for ( do {shift @derivative; @derivative} ) { # }

        -- Hofmator

Re: ignoring the first element of an array
by fruiture (Curate) on Feb 03, 2003 at 12:28 UTC

    You may a) use a flag variable b) omit foreach(@array) in favour of foreach(0 .. @array-1) or you could c) use a slice:

    foreach my $well ( @derivate[ 0 .. @derivate-1 ] ){ ...

    As you like it.

    --
    http://fruiture.de
Re: ignoring the first element of an array
by JaWi (Hermit) on Feb 03, 2003 at 12:30 UTC
    Hi,

    You could do this:

    my $well; foreach ( 1..$#derivative ) { $well = $derivative[ $_ ]; # blah blah blah }
    Hope it helps,

    -- JaWi

    "A chicken is an egg's way of producing more eggs."

Re: ignoring the first element of an array
by DaveH (Monk) on Feb 03, 2003 at 12:32 UTC

    Hi.

    There are a couple of different ways, depending on your particular favourite style. Once way is shown below.

    foreach my $well (@derivative[1..$#derivative]) { # blah blah blah }

    Hope that helps

    Cheers,

    -- Dave :-)


    $q=[split+qr,,,q,~swmi,.$,],+s.$.Em~w^,,.,s,.,$&&$$q[pos],eg,print