Slicing Array Elements in Perl

PERLServer Side ProgrammingProgramming Scripts

You can also extract a "slice" from an array - that is, you can select more than one item from an array in order to produce another array.

Example

 Live Demo

#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
@weekdays = @days[3,4,5];
print "@weekdays\n";

Output

This will produce the following result −

Thu Fri Sat

The specification for a slice must have a list of valid indices, either positive or negative, each separated by a comma. For speed, you can also use the .. range operator −

Example

 Live Demo

#!/usr/bin/perl
@days = qw/Mon Tue Wed Thu Fri Sat Sun/;
@weekdays = @days[3..5];
print "@weekdays\n";

Output

This will produce the following result −

Thu Fri Sat
raja
Updated on 28-Nov-2019 09:46:37

Advertisements