I am trying to complete a college assignment in Perl, and we’ve been told by our professor to use:
use strict;
use warnings;
With use strict; my code works perfectly. with use warnings;, however, my code spews all this stuff to SDOUT and I don’t know why (or how to shut it up). My relevant code is:
while($diff =~ /^(\d+)((,){1}(\d+))?([adc])(\d+)((,){1}(\d+))?/mgi) {
# This line is used for debugging the $diff regular expression scalars.
# print "\n1: $1\t2: $2\t 3: $3\t4: $4\t5: $5\t6: $6\t7: $7\t8: $8\t9: $9\n";
$difflinestotal += ($4 - $1) unless $4 == "";
$difflinestotal += ($9 - $6) unless $9 == "";
$difflinestotal += 1 if (($4 == "") && ($9 == ""));
}
With warnings, it spits this out in the middle of my output:
Argument "" isn't numeric in numeric eq (==) at ./partc.pl line 145.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 145.
Argument "" isn't numeric in numeric eq (==) at ./partc.pl line 146.
Argument "" isn't numeric in numeric eq (==) at ./partc.pl line 147.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 147.
Argument "" isn't numeric in numeric eq (==) at ./partc.pl line 147.
Use of uninitialized value $9 in numeric eq (==) at ./partc.pl line 146.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 145.
Use of uninitialized value $9 in numeric eq (==) at ./partc.pl line 146.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 147.
Use of uninitialized value $9 in numeric eq (==) at ./partc.pl line 147.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 145.
Use of uninitialized value $4 in numeric eq (==) at ./partc.pl line 147.
…and it’s messing up my formatting (I am generating a table in the console). I tried ‘declaring’ the scalars, but then (of course) those were in error. How can I get my Perl script to shut up with these warnings (especially since the works anyway)?
That goes to STDERR, not STDOUT.
Capture variables aren’t always set; if they aren’t, they will be undefined. For example, your regex has
((,){1}(\d+))?(where the(\d+)is the 4th capture). The?makes the whole group optional. If it is not used in matching the string, $3 and $4 will be left undefined.Where you are testing
unless $4 == ""you should be testingif defined $4.A couple other notes:
{1}does nothing; it says that the preceding part of the regular expression should match exactly once – which it would do without the{1}too. It can be easier to keep track of which capture variables you are using if you use non-capturing groups ((?: ... )) for the groupings you don’t need captured.