Why does Perl warn about "useless constant 1" when using bigint?
There are two issues at hand here.
- Why does
use bigint; 1;
warn in void context? - Why is the constant being executed in void context in the first place?
$ perl -c -we'1 while sub_with_side_effects();'
-e syntax OK
$ perl -c -we'use bigint; 1 while sub_with_side_effects();'
Useless use of a constant (1) in void context at -e line 1.
-e syntax OK
Why does use bigint; 1;
warn in void context?
use bigint;
installs a callback that's called when a constant literal is encountered by the parser, and the value returned by the callback is used as the constant instead. As such, under use bigint;
, 1
is no longer truly just a simple 0
or 1
.
But you're not doing anything wrong, so this warning is spurious. You can work around it by using ()
or undef
instead of 1
.
undef while sub_with_side_effects();
Unless I needed to use it throughout my code base, I would favour the following:
while ( sub_with_side_effects() ) { }
$ cat Module.pm
package Module;
use bigint;
1;
$ perl -c -w Module.pm
Useless use of a constant (1) in void context at Module.pm line 3.
Module.pm syntax OK
Why is the constant being executed in void context?
When Perl executes a module, Perl expects the module to return a scalar value, so Perl should be executing the module in scalar context.
However, you told Perl to compile the script Module.pm
. When Perl executes a script, Perl doesn't require any values to be returned, so Perl executes the script in void context.
Using a module as a script can cause spurious warnings and errors, and so can passing -W
. Test a module using as follows:
perl -we'use Module'
Actually, you shouldn't even need -w
since you should already have use warnings;
in the module. All you really need is
perl -e'use Module'
-W instead of use warnings;
in your module or checking modules with -c instead of perl -MFoo -e0
can show spurious errors. This is an example of the latter.
When you load a module normally, it isn't in void context, because it is checking that the result is true.
(Note that when I try it using 5.20.1, the -W also results in a spurious overload arg '..' is invalid at /usr/share/perl/5.20/Math/BigInt.pm line 155
.)