in reply to checking for piped input data
Use -p function to check if STDIN is a pipe (to read from standard input for the option; else require an argument for the option) ...
# Some time later, changed the code to collect all the input "do { ... + };", # not just the first line of STDIN. #!/usr/local/bin/perl use v5.26; use warnings; use Data::Dumper qw[ Dumper ]; use Getopt::Long; my $opt; GetOptions( 'opt:s' => \$opt ) or die $!; say Dumper( { 'Initial, opt' => $opt } ); if ( defined $opt ) { if ( -p STDIN ) { say q[Any option argument will be abandoned; collecting STDIN .. +.]; # Could process standard input line by line. # Here, all is collected at once. do { local $/; $opt = <STDIN> }; say Dumper( { ' ...after collecting STDIN, opt' => $opt } ); } elsif ( $opt eq '' ) { die qq[Neither a value was given for \$opt, nor was specified on + standard input.]; } else { say qq[STDIN is not a pipe; using existing \$opt = $opt.]; } } else { say qq[\$opt was not used, so STDIN was ignored.]; } say Dumper( { 'Final, opt' => $opt } );
Later shoved the output of various cases under readmore ...
Missing value for the option & no pipe ...
> perl stdin-pipe.pl --opt Neither a value was given for $opt, nor was specified on standard inpu +t. at stdin-pipe.pl line 25. # This is interesting for "say Dumper ... Initial" still runs # though "die" happens earlier. $VAR1 = { 'Initial, opt' => '' };
Only the value ...
> perl stdin-pipe.pl --opt Value $VAR1 = { 'Initial, opt' => 'Value' }; STDIN is not a pipe; using existing $opt = Value. $VAR1 = { 'Final, opt' => 'Value' };
Option value of X is ignored in preference to standard input ...
> date -u | perl stdin-pipe.pl --opt X $VAR1 = { 'Initial, opt' => 'X' }; Any option argument will be abandoned; collecting STDIN ... $VAR1 = { ' ...after collecting STDIN, opt' => 'Wed May 3 05:44:43 UT +C 2023 ' }; $VAR1 = { 'Final, opt' => 'Wed May 3 05:44:43 UTC 2023 ' };
No value for the option, with standard input ...
> date -u | perl stdin-pipe.pl --opt $VAR1 = { 'Initial, opt' => '' }; Any option argument will be abandoned; collecting STDIN ... $VAR1 = { ' ...after collecting STDIN, opt' => 'Wed May 3 06:24:29 UT +C 2023 ' }; $VAR1 = { 'Final, opt' => 'Wed May 3 06:24:29 UTC 2023 ' };
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: checking for piped input data
by Anonymous Monk on May 03, 2023 at 13:37 UTC | |
by parv (Parson) on May 04, 2023 at 03:21 UTC |