Home: Perl Programming Help: Beginner:
length() of undefined string



orange
User

Apr 25, 2014, 1:04 AM


Views: 3229
length() of undefined string

I would like to use length, so that it returns 0 when string is not defined, without a warning.

this produces no warning:

Code
print length($undefined);

but this:

Code
print 1+length($undefined);

gives warning: "Use of uninitialized value in addition (+)"
whats the simplest way of doing it?
thanks.


BillKSmith
Veteran

Apr 25, 2014, 5:51 AM


Views: 3222
Re: [orange] length() of undefined string

Use a do block to limit the scope of "no warnings".

Code
use strict; 
use warnings;
my @strings = ('a', 'ef', undef, 'ghij');
foreach my $sample (@strings){
do{
no warnings qw(uninitialized);
print 1 + length $sample;
};
print "\n";
}

OUTPUT
2
3
1
5


UPDATE: Added catagory "unitialized" to "no warnings" further restrict its influence.

Corrected previous update.
Good Luck,
Bill

(This post was edited by BillKSmith on Apr 26, 2014, 3:21 PM)


FishMonger
Veteran / Moderator

Apr 25, 2014, 6:22 AM


Views: 3219
Re: [orange] length() of undefined string


Code
print length($undefined) ? length($undefined) : 0;



FishMonger
Veteran / Moderator

Apr 25, 2014, 6:26 AM


Views: 3217
Re: [BillKSmith] length() of undefined string


Code
my @strings = ('a', 'ef', undef, 'ghij'); 
map{ say length($_) ? length($_) : 0 } @strings;



orange
User

Apr 25, 2014, 6:48 AM


Views: 3214
Re: [FishMonger] length() of undefined string

ok, thanks all.