Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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


Comment on Re: Can a defined value be of zero length?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1082901]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2014-11-29 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (203 votes), past polls