Question

I am posting this for the 1st time. I have gone through similar issues in the forum, but still I am not able to determine why I am getting this error.

Here is a sample code which I am trying to make..

use strict;
use warnings;
my ($m, $b) = @ARGV;
my $count_args = $#ARGV + 1;
my $times = 2**$m;
main();

sub main {
     if ( $m =~ /^\d+$/ ) {
         if ( $b =~ /^and$/i ) {
             func_and();    
         }   else {
             print " not supported\n";
         }
     }   else {
         print " enter valid number of pins\n";
     }
}
sub func_and {
    my $bit;
    for ( my $i = 0 ; $i < $times ; $i++ ) {
        my $p = sprintf( "%0${m}b", $i );    
        print "$p\t";
        my @c = split( '', $p );             
        my $result = 3;                      
        foreach  $bit (@c) {
            if ( $result < 3 ) {
                $result = $result && $bit;    
            } else {
                $result = $bit;    
            }
        }
        print "result for AND operation on $bit is $result \n";
    }
}

if i give the input as perl AND.pl 2 and

The error I get is Use of uninitialized value in concatenation (.) or string at NAND.pl line 34. is there any other way to declare the $ bit variable? and how can one initialize this? Thanks

Was it helpful?

Solution

Change:

print "result for AND operation on $bit is $result \n";

to:

print "result for AND operation on $p is $result \n";

Then, you can localize $bit to the foreach loop:

foreach my $bit (@c) {

perldoc perlsyn:

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop.

$bit was uninitialized before the loop, so it is still unchanged after the loop.

OTHER TIPS

The worst solution to this problem is to assign a value to $bit when you declare it.

my $bit = 0; # no!!!

While this gets around the error message it makes it difficult to find the logical error in your code. The warning message "use of uninitialized value..." is one of the most important debugging tools you have. If your code produces many such messages, you should turn your warnings into errors so the program halts at the first warning.

use warnings 'FATAL' => 'all';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top