Question

I'm having trouble using the perl splice() method. Bellow you will see that I first identify the indexes of the two strings that I am looking for and then perform splice() using the indexes to get the desired array.

My code is as follows:

my @a = qw(foo bar bazz elements in between hello bazz johnny bl aba);
my $z = 0;

for (my $i = 0; $i < @a; $i++)
{
    next unless $a[$i] =~ /bazz/;

    if( $z eq 0 )
    {
        $z++;
        $first = $i;
    }
    else
    {
        $second = $i;
    }               
    my @b = splice(@a,$first,$second);
    print Dumper(@b);
}

And the result of the print is as follows:

$VAR1 = 'bazz';
$VAR2 = 'elements';
$VAR3 = 'in';
$VAR4 = 'between';
$VAR5 = 'hello';
$VAR6 = 'bazz';
$VAR7 = 'johnny';

I was under the impression that splice takes the chunk in between the given limits, inclusive of course. I don't understand why element 'johnny' would be there. Shouldn't the list stop at the second 'bazz' ?

Thank you for any pointers on this issue.

Était-ce utile?

La solution

The second argument is the length of the slice, not the index of the end of the slice.

Autres conseils

splice takes the arguments as

splice @ARRAY, $OFFSET, $LENGTH, @REPLACE_LIST;

It removes $LENGTH elements from the @ARRAY starting at index $OFFSET and replaces them by the given list (or deletes them from the array when the empty list is (implicitely) given).

It seems you want an array slice instead:

my @b = @a[$first .. $second];
print Dumper \@b;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top