CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



orange
Novice

Apr 25, 2014, 1:04 AM

Post #1 of 5 (2459 views)
length() of undefined string Can't Post

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

Post #2 of 5 (2452 views)
Re: [orange] length() of undefined string [In reply to] Can't Post

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

Post #3 of 5 (2449 views)
Re: [orange] length() of undefined string [In reply to] Can't Post


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



FishMonger
Veteran / Moderator

Apr 25, 2014, 6:26 AM

Post #4 of 5 (2447 views)
Re: [BillKSmith] length() of undefined string [In reply to] Can't Post


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



orange
Novice

Apr 25, 2014, 6:48 AM

Post #5 of 5 (2444 views)
Re: [FishMonger] length() of undefined string [In reply to] Can't Post

ok, thanks all.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives