Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl complain "Useless use of a constant in void context", but only sometimes?

Here is my Perl script and its output:

use strict;
use warnings;

(undef, 1); # no output
(0, 1);     # no output
(1, 1);     # no output
(2, 1);     # "Useless use of a constant in void context at C:\...\void.pl line 7"
(3, 1);     # "Useless use of a constant in void context at C:\...\void.pl line 8"
("", 1);    # "Useless use of a constant in void context at C:\...\void.pl line 9"
("0", 1);   # "Useless use of a constant in void context at C:\...\void.pl line 10"
("1", 1);   # "Useless use of a constant in void context at C:\...\void.pl line 11"

I would expect warnings at every line. What is special about undef, 0 and 1 which causes this not to happen?

like image 877
qntm Avatar asked Jul 31 '13 21:07

qntm


1 Answers

Documented in perldoc perldiag complete with rationale:

This warning will not be issued for numerical constants equal to 0 or 1 since they are often used in statements like

1 while sub_with_side_effects();

As for undef, it's a function that has uses even in void context. e.g. undef($x) does something similar to —but different than— $x = undef();. (You normally want the latter.) A warning could be issued for uses of undef without args in void context, but it would require specialized code, and it's simply not needed.

like image 98
tjd Avatar answered Sep 28 '22 08:09

tjd