How do I make the STDIN in the Array stop? (PERL) -


this question has answer here:

my @array not stop taking in stdin...

my @array = undef; while (@array = undef){     @array = <stdin>;     (@array[x]=5){         @array = defined;     } } 

as clarified, limit stdin 5 lines

use warnings; use strict; use feature 'say';  @input;  while (<stdin>) {     chomp;     push @input, $_;     last if @input == 5; }  @input; 

there other things comment on in posted code. while deal of cleared in detail in dave cross answer, i'd address business of context when reading filehandle.

the "diamond" operator <> context-aware. i/o operators (perlop)

if <filehandle> used in context looking list, list comprising input lines returned, 1 line per list element. it's easy grow rather large data space way, use care.

in usual while loop <> in scalar context

while (my $line = <$fh>) 

and same while (<$fh>) since assigns $_ variable, scalar, default.

but if assign array, filehandle $fh file opened

my @lines = <$fh>; 

then <> operator works in list context. reads lines until sees eof (end-of-file), @ point returns lines, assigned @lines. remember each line has newline. can remove them

chomp @lines; 

since chomp works on list well.

with stdin raises issue when input comes keyboard, <> waits more input since eof isn't coming on own. given ctrl+d on unixy systems (ctrl+z on windows).

so can, in principle, have @array = <stdin> , quit input ctrl+d may little awkward input expected keyboard, implies need line line processing. less unusual if stdin comes file,

script.pl < input.txt 

or pipe on command line

some command output | script.pl 

where eof (courtesy of eot).

but i'd still stick customary while when reading stdin, , process line line.


  ctrl+d how referred 1 types low-case d ctrl. note ctrl , c (labeled ctrl+c) entirely different; sends sigint signal, terminates whole program if not caught.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -