Question

my @writers = qw( Horace Ovid Virgil Asimov Heinlein Dante );
my @contemporary = splice @writers, 3, 2;
print join(' ', @contemporary);

output

Asimov Heinlein

 


my @writers = qw( Horace Ovid Virgil Asimov Heinlein Dante );
splice @writers, 3, 2;
print join(' ', @writers); # Horace Ovid Virgil Dante

output

Horace Ovid Virgil Dante

What is the difference between these scripts. Why it showing different output?

Était-ce utile?

La solution

here

 my @contemporary = splice @writers, 3, 2;
 print join(' ', @contemporary);

it returns the elements that has been removed

while here

splice @writers,3,2;
print join(' ', @writers)

it just print the elements of the array

and in a scalar context for example

 my $contemporary = splice @writers, 3, 2;
 print $contemporary;

it will print the last element that has been removed

from perldoc

Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or undef if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, Perl issues a warning, and splices at the end of the array.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top