Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print first few elements of a list in perl

Tags:

perl

Have a next perl code

use 5.012;
use warnings;

#make some random numbers
my @list = map { rand } 1..10;

say "print all 10 numbers";
say $_ for @list;

say "print only first 5";
my $n=0;
for (@list) {
        say $_ if $n++ < 5;
}

some more compact form for printing first (last) N elements of any array?

the next is syntax error...

$n=0;
#say $_ if($n++ < 5) for @list;
like image 574
jm666 Avatar asked Jul 19 '13 18:07

jm666


People also ask

How do I get the first element of a list in Perl?

A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list).

How do I slice an array in Perl?

Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values. print "Extracted elements: " .

What does Unshift do in Perl?

unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.

How do I append a list in Perl?

push(@array, element) : add element or elements into the end of the array. $popped = pop(@array) : delete and return the last element of the array. $shifted = shift(@array) : delete and return the first element of the array. unshift(@array) : add element or elements into the beginning of the array.


2 Answers

To print the first 5 items:

say for @list[0 .. 4];

To print the last 5 items:

say for @list[-5 .. -1];
like image 133
AKHolland Avatar answered Oct 26 '22 23:10

AKHolland


Just use a list slice:

#!/usr/bin/perl
use strict;

my @list = map { int(rand*10) } 1..10;
print join(', ', @list[0..4]) . "\n";

Also, use strict, without exception, unless you really enjoy spending far too much time hunting down subtle scoping bugs.

like image 23
Aaron Miller Avatar answered Oct 26 '22 23:10

Aaron Miller