tags:

views:

1482

answers:

8

I currently use the following Perl to check if a variable is defined and contains text. I have to check defined first to avoid an 'uninitialized value' warning:

if (defined $name && length $name > 0) {
    # do something with $name
}

Is there a better (presumably more concise) way to write this?

+2  A: 

You could say

 $name ne ""

instead of

 length $name > 0
mobrule
This will still give you a warning. The reason people check definedness first is to avoid the 'uninitialized value' warning.
brian d foy
+5  A: 

As mobrule indicates, you could use the following instead for a small savings:

if (defined $name && $name ne '') {
    # do something with $name
}

You could ditch the defined check and get something even shorter, e.g.:

if ($name ne '') {
    # do something with $name
}

But in the case where $name is not defined, although the logic flow will work just as intended, if you are using warnings (and you should be), then you'll get the following admonishment:

Use of uninitialized value in string ne

So, if there's a chance that $name might not be defined, you really do need to check for definedness first and foremost in order to avoid that warning. As Sinan Ünür points out, you can use Scalar::MoreUtils to get code that does exactly that (checks for definedness, then checks for zero length) out of the box, via the empty() method:

use Scalar::MoreUtils qw(empty);
if(not empty($name)) {
    # do something with $name 
}
Adam Bellaire
+1  A: 

It isn't always possible to do repetitive things in a simple and elegant way.

Just do what you always do when you have common code that gets replicated across many projects:

Search CPAN, someone may have already the code for you. For this issue I found Scalar::MoreUtils.

If you don't fined something you like on CPAN, make a module and put the code in a subroutine:

package My::String::Util;
use strict;
use warnings;
our @ISA = qw( Exporter );
our @EXPORT = ();
our @EXPORT_OK = qw( is_nonempty);

use Carp  qw(croak);

sub is_nonempty ($) {
    croak "is_nonempty() requires an argument" 
        unless @_ == 1;

    no warnings 'uninitialized';

    return( defined $_[0] and length $_[0] != 0 );
}

1;

=head1 BOILERPLATE POD

blah blah blah

=head3 is_nonempty

Returns true if the argument is defined and has non-zero length.    

More boilerplate POD.

=cut

Then in your code call it:

use My::String::Util qw( is_nonempty );

if ( is_nonempty $name ) {
    # do something with $name
}

Or if you object to prototypes and don't object to the extra parens, skip the prototype in the module, and call it like: is_nonempty($name).

daotoad
Isn't this like using a hammer to kill a fly?
Zoran Simic
@Zoran No. Factoring code out like this beats having a complicated condition replicated in many different places. That would be like using pinpricks to kill an elephant. @daotoad: I think you should shorten your answer to emphasize the use of `Scalar::MoreUtils`.
Sinan Ünür
@Zoran: Scalar::MoreUtils is a very lightweight module with no dependencies. Its semantics are also well known. Unless you are allergic to CPAN, there's not much reason to avoid using it.
Adam Bellaire
@daotoad - Since you've prototyped your `is_nonempty` to `($)` Perl will warn _at compile time_ when the function is called with the wrong number of arguments. You shouldn't need to do that at runtime.
Chris Lutz
daotoad
It's easier to think about prototypes as hints to the perl compiler so it knows how to parse something. They aren't there to validate arguments. They may be broken in terms of people's expectations, but so many things are. :)
brian d foy
A: 

How about

if (length ($name || '')) {
  # do something with $name
}

This isn't quite equivalent to your original version, as it will also return false if $name is the numeric value 0 or the string '0', but will behave the same in all other cases.

In perl 5.10 (or later), the appropriate approach would be to use the defined-or operator instead:

use feature ':5.10';
if (length ($name // '')) {
  # do something with $name
}

This will decide what to get the length of based on whether $name is defined, rather than whether it's true, so 0/'0' will handle those cases correctly, but it requires a more recent version of perl than many people have available.

Dave Sherohman
Why lead off with a broken solution only to say that it is broken?
brian d foy
Because, as I also mentioned, 5.10 is "a more recent version of perl than many people have available." YMMV, but "this is a 99% solution that I know you can use, but there's a better one that maybe you can use, maybe you can't" seems better to me than "here's the perfect solution, but you probably can't use it, so here's an alternative you can probably get by with as a fallback."
Dave Sherohman
Even with earlier perls you can have a working solution instead of a broken one.
brian d foy
+4  A: 

First, since length always returns a non-negative number,

if ( length $name )

and

if ( length $name > 0 )

are equivalent.

If you are OK with replacing an undefined value with an empty string, you can use Perl 5.10's //= operator which assigns the RHS to the LHS unless the LHS is defined:

#!/usr/bin/perl

use feature qw( say );
use strict; use warnings;

my $name;

say 'nonempty' if length($name //= '');
say "'$name'";

Note the absence of warnings about an uninitialized variable as $name is assigned the empty string if it is undefined.

However, if you do not want to depend on 5.10 being installed, use the functions provided by Scalar::MoreUtils. For example, the above can be written as:

#!/usr/bin/perl

use strict; use warnings;

use Scalar::MoreUtils qw( define );

my $name;

print "nonempty\n" if length($name = define $name);
print "'$name'\n";

If you don't want to clobber $name, use default.

Sinan Ünür
+1 for "//=" mention (how'd I know that'd be Sinan's answer :)
DVK
I wouldn't use //= in this case since it changes the data as a side effect. Instead, use the slightly shorter `length( $name // '' )`.
brian d foy
@brian d'foy I think it depends on what is being done in the function.
Sinan Ünür
+1 The `//` and `//=` operators are possibly the most useful specialized operators in existence.
Chris Lutz
+10  A: 

You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):

 Use of uninitialized value $name in ...

So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:

 {
 no warnings 'uninitialized';

 if( length $name ) {
      ...
      }
 }

In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:

 use 5.010;

 if( length( $name // '' ) ) {
      ...
      }
brian d foy
A: 

In cases where I don't care whether the variable is undef or equal to '', I usually summarize it as:

$name = "" unless defined $name;
if($name ne '') {
  # do something with $name
}
Gaurav
In Perl 5.10, this can be shortened to `$name //= "";` which is exactly what Sinan posted.
Chris Lutz
And even if you don't have perl 5.10, you can still write `$name ||= "";`
RET
@RET: you can't use the || operator here since it replaces the string '0' with ''. You have to check if it is defined, not true.
brian d foy
Chris, RET: Yup, I know. I was specifically trying to suggest that if Jessica was not concerned with the difference between `undef` and `""`, she should just change one to the other and use a single test. This won't work in the general case, for which the other solutions posted are way better, but in this specific case leads to neat code. Should I rephrase my answer to make this clearer?
Gaurav
+1  A: 
if ($name )
{
    #since undef and '' both evaluate to false 
    #this should work only when string is defined and non-empty...
    #unless you're expecting someting like $name="0" which is false.
    #notice though that $name="00" is not false
}
Joseph
Unfortunately this will be false when $name = 0;
Mike Wade
yep, you're right
Joseph