Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

perl - convert 0 into string

i'm working on a script in perl.

This script read a DB and generate config file for other devices.

I have a problem with "0".

From my database, i get a 0 (int) and i want this 0 become a "0" in the config file. When i get any other value (1,2,3, etc), the script generate ("1","2","3", etc). But the 0 become an empty string "".

I know, for perl:
- undef
- 0
- ""
- "0"
are false.

How can i convert a 0 to "0" ? I try qw,qq,sprintf, $x = $x || 0, and many many more solutions.

I juste want to make a explicit conversion instead of an implicite conversion.

Thank you for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you think you have zero, but the program thinks you have an empty string, you are probably dealing with a dualvar. A dualvar is a scalar that contains both a string and a number. Perl usually returns a dualvar when it needs to return false.

For example,

$ perl -we'my $x = 0; my $y = $x + 1; CORE::say "x=$x"'
x=0

$ perl -we'my $x = ""; my $y = $x + 1; CORE::say "x=$x"'
Argument "" isn't numeric in addition (+) at -e line 1.
x=

$ perl -we'my $x = !1; my $y = $x + 1; CORE::say "x=$x"'
x=

As you can see, the value returned by !1 acts as zero when used as a number, and acts as an empty string when used as a string.

To convert this dualvar into a number (leaving other numbers unchanged), you can use the following:

$x ||= 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...