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;
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).
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: " .
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.
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.
To print the first 5 items:
say for @list[0 .. 4];
To print the last 5 items:
say for @list[-5 .. -1];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With