Print the first few list items in perl

You have the following 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; } 

a slightly more compact form for printing the first (last) N elements of any array?

following syntax error ...

 $n=0; #say $_ if($n++ < 5) for @list; 
+4
source share
4 answers

To print the first 5 elements:

 say for @list[0 .. 4]; 

To print the last 5 items:

 say for @list[-5 .. -1]; 
+10
source

Just use a list snippet :

 #!/usr/bin/perl use strict; my @list = map { int(rand*10) } 1..10; print join(', ', @list[0..4]) . "\n"; 

Also, use strict , without exception, if you really don't like spending too much time looking for subtle errors.

+3
source

Another way to write it is with a while .

 my $i = 0; say $list[$i++] while $i < 5; 
+2
source

In addition, the destructive approach:

 splice @list, 5; say for @list; 
-one
source

Source: https://habr.com/ru/post/1492375/


All Articles