Search code examples
perldivide-by-zero

Illegal division by zero on very simple script


A simple perl script:

#!/usr/bin/perl
$num = `sed "s/\([^ ]*\).*/\1/"`;
print "$num";

$total = `sed "s/[^ ]*\(.*\)/\1/"`;
print "$total";

$div = $num / $total;
print "div = $div \n";

When I run it:

$ echo 4 10 | ./test.pl 
4 10
Illegal division by zero at ./test.pl line 11.

Solution

  • Change the code like this and the answer will be obvious:

    #!/usr/bin/perl
    
    $num = `sed "s/\([^ ]*\).*/\1/"`;
    
    print "num = $num\n";
    
    $total = `sed "s/[^ ]*\(.*\)/\1/"`;
    
    print "total = $total\n";
    
    $div = $num / $total;
    
    print "div = $div\n";