Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki MarkupPerl's comma operator {{,}} performs several duties. The most widely - known duty is to serve as a list separator. These are referred to as "fat commas" \[[Conway 05|AA. Bibliography#Conway 05]\].separator:

Code Block

my @list = (2, 3, 5, 7);

Wiki MarkupOutside of list context, the comma can also be used to combine multiple expressions into one statement. Each expression is evaluated , and its result is discarded. The last expression's result is returned as the result of the comma operator. These are referred to as "thin commas" \[[Conway 05|AA. Bibliography#Conway 05]\]. This behavior was adopted from  Comma operators are called thin commas [Conway 2005]. This behavior was adopted from C.

The potential for confusing thin commas with fat commas in list context is large enough to forbid use of the thin commas. Commas shall only must be used to only to separate items in list context.

...

This code example validates a file , and indicates if it exists.

Code Block
bgColor#ffcccc
langperl

sub validate_file {
  my $file = shift(@_);
  if (-e $file) {
    return 1; # file exists
  }
  die "$file does not exist";
}

my $file = $ARGV[0];
validate_file($file), print "hi!\n";

This code behaves as expected. The comma operator is used to separate out the call to validate_file and subsequent call to print in the same statement. ThusConsequently, the return value of validate_file is discarded before print is called.

This line of code looks like it would behave the same , but instead behaves quite differently:

Code Block
bgColor#ffcccc
langperl

print validate_file($file), "hi!\n";

The print statement takes a list of items to print, and, in list context, the comma operator is assumed to separate list items. Consequently, if the file is valid, this program prints 1 before its friendly greeting.

...

Code Block
bgColor#ccccff
langperl

validate_file($file);
print "hi!\n";

...

If multiple functions must be invoked within one statement, a do block can be used to evaluate a list of expressions , without using list context.

Code Block
bgColor#ccccff
langperl

print do { validate_file($file); "hi!\n"};

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC30-PL

low Low

probable Probable

medium Medium

P2 P4

L3

Automated Detection

Tool

Diagnostic

Perl::Critic

ValuesAndExpressions::ProhibitCommaSeparatedStatements

Bibliography

...

[

...

...

 

...

Image AddedImage AddedImage Added|http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/ValuesAndExpressions/ProhibitCommaSeparatedStatements.pm]Image Removed      01. Declarations and Initialization      DCL32-PL. Every module must return a true value