Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Shortcut for if(defined($var) && $var ne "") ?

4 views
Skip to first unread message

vik...@gmail.com

unread,
Apr 6, 2008, 2:53:09 AM4/6/08
to
Is there shorter equivalent of if(defined($var) && $var ne "")
that doesn't fall for the "0" case, and doesn't produce warning with -
w ?

Thanks
V.M.

Johann Kappacher

unread,
Apr 6, 2008, 4:34:40 AM4/6/08
to
Hmm,

if (length $var) ....

--jk

Johann Kappacher

unread,
Apr 6, 2008, 4:41:46 AM4/6/08
to
Sorry,

it will produce warnings if it is not initialized.
If you want to avoid warnings you must use defined().

perl 5.10 introduces the defined-or Operator.
=> This is your solution.

--jk

Chris Mattern

unread,
Apr 6, 2008, 12:50:58 PM4/6/08
to

I tried this test program:

#!/usr/bin/perl

use warnings;
use strict;

my $var;

if (defined($var) && $var ne "") {
print "$var\n";
}

It didn't produce any warnings. When I put in "my $var = 0;",
it printed "0", just like it should. I don't understand
your question. If by "shorter" you mean getting rid of the
defined() test, then, no, you can't get rid of that. If you
aren't sure if $var is going to be defined, you have to test
for it before trying to use it.

--
Christopher Mattern

NOTICE
Thank you for noticing this new notice
Your noticing it has been noted
And will be reported to the authorities

Johann Kappacher

unread,
Apr 6, 2008, 1:47:24 PM4/6/08
to

... but no, you need a defined-and operator!
I give up, this exercise is futile!

Abigail

unread,
Apr 7, 2008, 5:40:07 AM4/7/08
to
_
Chris Mattern (sys...@sumire.gwu.edu) wrote on VCCCXXXII September
MCMXCIII in <URL:news:slrnfvhvri...@sumire.gwu.edu>:

{} On 2008-04-06, vik...@gmail.com <vik...@gmail.com> wrote:
{} > Is there shorter equivalent of if(defined($var) && $var ne "")
{} > that doesn't fall for the "0" case, and doesn't produce warning with -
{} > w ?
{} >
{} > Thanks
{} > V.M.
{}
{} I tried this test program:
{}
{} #!/usr/bin/perl
{}
{} use warnings;
{} use strict;
{}
{} my $var;
{}
{} if (defined($var) && $var ne "") {
{} print "$var\n";
{} }
{}
{} It didn't produce any warnings. When I put in "my $var = 0;",
{} it printed "0", just like it should. I don't understand
{} your question. If by "shorter" you mean getting rid of the
{} defined() test, then, no, you can't get rid of that. If you
{} aren't sure if $var is going to be defined, you have to test
{} for it before trying to use it.


Shorter:

if (length ($var // "")) { .. }

Abigail
--
perl -we 'print split /(?=(.*))/s => "Just another Perl Hacker\n";'

0 new messages