Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Can a defined value be of zero length?

by graff (Chancellor)
on Apr 19, 2014 at 15:27 UTC ( #1082901=note: print w/replies, xml ) Need Help??

in reply to Can a defined value be of zero length?

In the OP script, the defined $pattern condition is entirely unnecessary; the length $pattern condition is sufficient because $pattern will be used as a string, so all that matters is that the string not be empty (and "undef" variables are equivalent to empty strings when passed to length()).

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:

#!/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 ); }
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).

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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1082901]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2018-06-18 16:15 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (110 votes). Check out past polls.