Using Dumper not triggering a failure

2020-03-06 07:28发布

when running code like this:

use strict;
print Dumper "something";

nothing is printed out and no error occurs during compile and runtime. Why does this happen? Why doesn't strict prevent this code from running? Why is there no error at runtime, even though Dumper is unknown?

I know it produces a warning when those are explicitly enabled, but I'm interested why is this code considered "correct" in any way.

2条回答
小情绪 Triste *
2楼-- · 2020-03-06 08:05

If you had begun with the standard boilerplate, then you would know:

#!/usr/bin/env perl
#
# name_of_program - what the program does as brief one-liner
#
# Your Name <your_email@your_host.TLA>
# Date program written/released
#################################################################

use 5.10.0;

use utf8;
use strict;
use autodie;
use warnings FATAL => "all";

#  ⚠ change to agree with your input: ↓
use open ":std" => IN    => ":encoding(ISO-8859-1)",
                   OUT   => ":utf8";
#  ⚠ change for your output: ↑ — *maybe*, but leaving as UTF-8 is sometimes better

END {close STDOUT}

our $VERSION = 1.0;

$| = 1;

The answer is that your program is syntactically but not semantically correct. You are printing "something" to the unopened Dumper filehandle-object, because Dumper is in the dative slot for the print method call. That makes Dumper print’s invocant. But you never opened a handle by that name, so you are printing to an uninitialized filehandle.

Use my boilerplate. PLEASE!

查看更多
▲ chillily
3楼-- · 2020-03-06 08:11

One of the valid syntaxes for print is

print FILEHANDLE LIST

In your program Perl is treating Dumper as a filehandle glob.

Running this code with warnings enabled will tell you:

print() on unopened filehandle Dumper at ...

查看更多
登录 后发表回答