質問

Suppose we have the following code :

#!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() ;

but i want to store just 3 elements from the user's input into my @arr array , how to do that , in general how to limit the size of a given array ?

役に立ちましたか?

解決

To store just 3 lines, you can use

my $i = 1;
while (defined( my $line = <STDIN>) and $i++ <=3) {
    push @arr, $line;
}

As for the second question, what do you mean by limiting the size of an array? You can use an array slice to get just the first three elements of an array:

my @first_three = @arr[0 .. 2];

他のヒント

#!usr/bin/perl

use strict ;
use warnings ;

sub print_ele_arr {

  my @arr;
  while (@arr < 3) {
    push @arr, scalar <STDIN>;
  }

  # chomp(@arr); # remove newlines from @arr elements?
  print "@arr\n";
}

print_ele_arr() ;

When reading from STDIN or any other input file handle there are two ways to it, doing it in scalar or list context.

List context forces reading all lines at once, and scalar reads one line at the time. Since STDIN doesn't have fixed size, it's better to force scalar context, using scalar function.

This is necessary when populating array, and redundant when populating plain scalar, ie.

my $single_line = <STDIN>;

is same thing as writing

my $single_line = scalar <STDIN>;

i mean something like preventing the user from typing more than 3 elements ?

No. There's no way for a computer to control a person or to physically lock the keyboard. They can type away all they want. They could even have typed more than three lines before you even read the first.

You have two options:

  1. Read only the first three lines.

    my @lines;
    while (<>) {
       push @lines, $_;
       last if @lines == 3;
    }
    
    die "Bad input" if @lines < 3;
    
  2. Throw an error if he types in more than three lines before sending an EOF.

    my @lines;
    while (<>) {
       die "Bad input" if @lines > 3;
       push @lines, $_;
    }
    
    die "Bad input" if @lines < 3;
    
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top