Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Zero's vs Null

Status
Not open for further replies.

fortuneman

Technical User
Oct 27, 2000
10
US
Wrote a little loop to calculate the dec from binary. Problem is that the !$bin matches if $bin is "null" or "zero". I don't want it to match zero. I need a way to get zero to pass through but I'm unsure of an easy way to do this. Additionally, chomp complains too if $bin is null as well. Appreciate any assistance. Thanks.

Code:
use strict;

my $bin= shift;
chomp($bin);
my @answer;
my $dec = 0;

if (!$bin|| $bin !~ (/^[01]*$/)) {
        print &quot;Usage: decTobin.pl <decimal value>&quot;;
        exit(0);
}

@answer = split(//, $bin);
find_dec(@answer);
print $dec;

###########
#Find binary position
###########
sub find_dec{
        my $count = 0;
        foreach (reverse(@answer)) {
           $dec = ($dec + ($_ * (2**$count)));
           $count++
        }
}
 
Change the condition line to this:

unless ( $bin =~ /[^01]/ || ! defined($_) ) {

--jim
 
That still has a problem if you don't pass any arguments. You get a warning when the interpreter tried to do a condition match on a null variable. I've changed the code to the following....it works but I had to turn off warnings....

Code:
#!perl

use strict;

my $bin= shift;
my @answer;
my $dec = 0;

if ((!$bin && $bin !~ /0/) || $bin !~ (/^[01]*$/)) {
        print &quot;Usage: binTodec.pl <decimal value>&quot;;
        exit(0);
}

@answer = split(//, $bin);
find_dec(@answer);
print $dec;

###########
#Find binary position
###########
sub find_dec{
        my $count = 0;
        foreach (reverse(@answer)) {
           $dec = ($dec + ($_ * (2**$count)));
           $count++
        }
}
 
Perl's &quot;null&quot; value is undef, and to check that, use the defined() builtin. Zero and the empty string are defined values, undef is the only thing that's not.

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
You're the man!! ;) Thanks. I guess I was thinking that !$var was the same thing but obviously not. Works like a charm...with the warnings on. Thanks again.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top