Mario
Mario

Reputation: 55

Perl::Critic in Brutal Mode

So I've recently started using Perl::Critic to check the quality of the code I've written. I'm running it in brutal mode and have one suggestion it is making which I don't understand as being an issue. The output is:

Return value of flagged function ignored - print at line 197, column 13. See pages 208,278 of PBP. (Severity: 1)

This is basically a call to the print function with a short message which outputs to the console. Why then should I capture the return value which will almost certainly always be 1 as I can't think of any use case where this wouldn't be a 1.

Is brutal mode being 'too brutal'? Or am I missing something? I should add that I did read pages 208 and 278 of the PBP and the answer is not clear to me.

Upvotes: 3

Views: 780

Answers (3)

Archimedes Trajano
Archimedes Trajano

Reputation: 41300

To implement the fix for

print "$updated_service_name\n";

Use

my $printed = (print "$updated_service_name\n");
if (!$printed) {
  die "Unable to write to stdout\n";
}

Upvotes: -1

BarneySchmale
BarneySchmale

Reputation: 780

One use case where print "something"; fails is when STDOUT has been opened to a file and the file system is full. But in my projects I also do not check the return value of print.

Upvotes: 2

toolic
toolic

Reputation: 62054

I agree that most of the time print will not fail. But, you can disable this function by creating a .perlcriticrc file and adding these lines to it (like I do):

# Check all builtins except "print"
[InputOutput::RequireCheckedSyscalls]
functions = :builtins
exclude_functions = print

This is described in Perl::Critic::Policy::InputOutput::RequireCheckedSyscalls

Also, if you disagree with all the policies of the Brutal setting, you can just use one of the other 4 less brutal settings. The tool is highly configurable.

Here is a trivial case where print can fail (printing to a closed filehandle):

open my $fh, '>', 'out';
print $fh "555\n";
close $fh;
print $fh "888\n" or die "print failed: $!";

# we shouldn't get here
print "777\n";

In such short code, it is obvious that you just closed the filehandle, and you would never then try to print to it. But, if you had a lot of (poorly designed) code, maybe it would occur.

There are other reasons print could fail, such as if another process came along and deleted a directory or disabled write permissions on your open file.

I created a script for myself to run perlcritic which makes it easy to access the POD for a given policy: Sort and summarize perlcritic output

Upvotes: 6

Related Questions