If you pipe data to the script (e.g. echo fs | your_script), you'll get the prompt string, followed by the expected output, followed by a warning (Use of unitialized value $pattern in chomp…). You also get that warning if you run it "normally" (not piping to its STDIN) and hit control-D to signal end-of-input on STDIN. For "clean" operation, I'd write it like this:
That relies on the "special" behavior of the file-input operator (angle brackets around a file handle) when used as the conditional portion of a "while" statement: the result is false (the loop exits) when the input operator returns "undef" (due to an end-of-file condition). See the "I/O Operators" section of the "perlop" man page (perl operators).#!/usr/bin/perl use strict; use warnings; my $dir = '/etc'; my $prompt = ( -t ) ? 'Enter pattern> ' : ''; print $prompt; while ( my $pattern = <STDIN>) { $pattern =~ s/\s+$//; last unless length( $pattern ); my @matched = eval { grep { /$pattern/ } glob "$dir/*"; }; print "Error: $@" if $@; print join( "\n", @matched, $prompt ); }
My version also checks whether input is coming from a terminal (as opposed to a pipe), and prints "Enter pattern >" only in that case (so that the output with pipeline usage is not contaminated by the prompting text).
I'm tempted to add $pattern =~ s/^\s+//; as well, given that I don't expect any file names in /etc to start with white space, and when reading from a keyboard, it's not unlikely to get initial as well as final spaces that are typed in by mistake.
Update: It's definitely worthwhile to read the more careful explanation in kcott's reply later in this thread (++ to that).
In reply to Re: Can a defined value be of zero length?
by graff
in thread Can a defined value be of zero length?
by reisinge
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |