Jac*_*erl 3 perl perl-data-structures
假设我们有以下代码:
#!usr/bin/perl
use strict ;
use warnings ;
sub print_ele_arr{
my @arr = <STDIN> ;
#print the elements of the array here .
#do something else ..
}
print_ele_arr() ;
Run Code Online (Sandbox Code Playgroud)
但我想将用户输入中的3个元素存储到我的@arr数组中,如何做到这一点,一般如何限制给定数组的大小?
要存储3行,您可以使用
my $i = 1;
while (defined( my $line = <STDIN>) and $i++ <=3) {
push @arr, $line;
}
Run Code Online (Sandbox Code Playgroud)
至于第二个问题,限制数组大小是什么意思?您可以使用数组切片来获取数组的前三个元素:
my @first_three = @arr[0 .. 2];
Run Code Online (Sandbox Code Playgroud)