The Perl Toolchain Summit 2025 Needs You: You can help 🙏 Learn more

##############################################################################
# $Date: 2009-06-27 20:02:58 -0400 (Sat, 27 Jun 2009) $
# $Author: clonezone $
# $Revision: 3373 $
##############################################################################
use 5.006001;
use strict;
use English qw( -no_match_vars );
qw{ :characters :severities :data_conversion :booleans };
our $VERSION = '1.099_002';
#-----------------------------------------------------------------------------
Readonly::Scalar my $DESC => q{Magic punctuation variable used};
Readonly::Scalar my $EXPL => [79];
#-----------------------------------------------------------------------------
# There is no English.pm equivalent for $].
sub supported_parameters {
return (
{ name => 'allow',
description => 'The additional variables to allow.',
default_string => $EMPTY,
behavior => 'string list',
list_always_present_values =>
[qw( $_ @_ $1 $2 $3 $4 $5 $6 $7 $8 $9 _ $] )],
},
{ name => 'string_mode',
description =>
'Controls checking interpolated strings for punctuation variables.',
default_string => 'thorough',
behavior => 'enumeration',
enumeration_values => [qw{ simple disable thorough }],
enumeration_allow_multiple_values => 0,
},
);
}
sub default_severity { return $SEVERITY_LOW }
sub default_themes { return qw(core pbp cosmetic) }
sub applies_to {
return qw( PPI::Token::Magic
PPI::Token::Quote::Double
PPI::Token::Quote::Interpolate
PPI::Token::QuoteLike::Command
PPI::Token::QuoteLike::Backtick
PPI::Token::QuoteLike::Regexp
PPI::Token::QuoteLike::Readline
PPI::Token::HereDoc
);
}
#-----------------------------------------------------------------------------
# sub initialize_if_enabled{} is not used
#-----------------------------------------------------------------------------
# Private entities
# The main regular expression for detecting magic variables
Readonly::Scalar my $_MAGIC_REGEXP => _create_magic_detector();
# The magic vars in this array will be ignored in interpolated strings
# in simple mode. See CONFIGURATION in the pod.
Readonly::Array my @IGNORE_FOR_INTERPOLATION =>
( q{$'}, q{$$}, q{$#}, q{$:}, ); ## no critic ( RequireInterpolationOfMetachars )
#-----------------------------------------------------------------------------
sub violates {
my ( $self, $elem, undef ) = @_;
if ( $elem->isa('PPI::Token::Magic') ) {
return _violates_magic( $self, $elem );
}
elsif ( $elem->isa('PPI::Token::HereDoc') ) {
return _violates_heredoc( $self, $elem );
}
#the remaining applies_to() classes are all interpolated strings
return _violates_string( $self, $elem );
}
#-----------------------------------------------------------------------------
# Helper functions for the three types of violations: code, quotes, heredoc
sub _violates_magic {
my ( $self, $elem, undef ) = @_;
if ( !exists $self->{_allow}->{$elem} ) {
return $self->violation( $DESC, $EXPL, $elem );
}
return; # no violation
}
sub _violates_string {
my ( $self, $elem, undef ) = @_;
my %matches = _strings_helper( $self, $elem->content() );
if (%matches) {
my $DESC = qq{$DESC in interpolated string};
return $self->violation( $DESC, $EXPL, $elem );
}
return; # no violation
}
sub _violates_heredoc {
my ( $self, $elem, undef ) = @_;
if ( $elem->{_mode} eq 'interpolate' or $elem->{_mode} eq 'command' ) {
my $heredoc_string = join qq{\n}, $elem->heredoc();
my %matches = _strings_helper( $self, $heredoc_string );
if (%matches) {
my $DESC = qq{$DESC in interpolated here-document};
return $self->violation( $DESC, $EXPL, $elem );
}
}
return; # no violation
}
#-----------------------------------------------------------------------------
# Helper functions specific to interpolated strings
sub _strings_helper {
my ( $self, $target_string, undef ) = @_;
return if ( $self->{_string_mode} eq 'disable' );
return _strings_thorough( $self, $target_string )
if $self->{_string_mode} eq 'thorough';
# we are in string_mode = simple
my @raw_matches = $target_string =~ m/$_MAGIC_REGEXP/goxms;
return if ( !@raw_matches );
my %matches;
@matches{@raw_matches} = 1;
delete @matches{ keys %{ $self->{_allow} } };
delete @matches{@IGNORE_FOR_INTERPOLATION};
return %matches;
}
sub _strings_thorough {
my ( $self, $target_string, undef ) = @_;
my %matches;
MATCH:
while ( my ($match) = $target_string =~ m/$_MAGIC_REGEXP/gcxms ) {
my $nextchar = substr $target_string, $LAST_MATCH_END[0], 1;
my $c = $match . $nextchar;
# These tests closely parallel those in PPI::Token::Magic,
# from which the regular expressions were taken.
# A degree of simplicity is sacrificed to maintain the parallel.
# $c is so named by analogy to that module.
if ( $c =~ m/ ^ \$ .* [ \w : \$ \{ ] $ /xms
) # possibly *not* a magic variable
{
## no critic (RequireInterpolationOfMetachars)
if ( $c =~ m/ ^(\$(?:\_[\w:]|::)) /xms
or $c =~ m/ ^\$\'[\w] /xms )
{
next MATCH
if $c !~ m/ ^\$\'\d$ /xms;
# It not $' followed by a digit.
# So it's magic var with something immediately after.
}
next MATCH
if $c =~ m/ ^\$\$\w /xms; # It's a scalar dereference
next MATCH
if $c eq '$#$'
or $c eq '$#{'; # It's an index dereferencing cast
next MATCH
if $c =~ m/ ^(\$\#)\w /xms
; # It's an array index thingy, e.g. $#array_name
# PPI's checks for long escaped vars like $^WIDE_SYSTEM_CALLS
# appear to be erroneous, and are omitted here.
# if ( $c =~ m/^\$\^\w{2}$/xms ) {
# }
next MATCH if $c =~ m/ ^\$\#\{ /xms; # It's a $#{...} cast
}
# The additional checking that PPI::Token::Magic does at this point
# is not necessary here, in an interpolated string context.
$matches{$match} = 1;
}
delete @matches{ keys %{ $self->{_allow} } };
return %matches;
}
#-----------------------------------------------------------------------------
sub _create_magic_detector{
my $config = shift;
my %_magic_vars;
@_magic_vars{
keys %PPI::Token::Magic::magic } ## no critic (ProhibitPackageVars)
= 1;
# Set up the regexp alternation for matching magic variables.
# We can't process $config->{_allow} here because of a quirk in the
# way Perl::Critic handles testing.
#
# The sort is needed so that, e.g., $^ doesn't mask out $^M
my $magic_alternation = '(?:'
. (
join q(|),
map { quotemeta $_ }
sort { -( length $a <=> length $b ) }
keys %_magic_vars
) . ')';
return qr{
(?: \A | [^\\] ) # beginning-of-string or any non-backslash
(?: \\\\ )* # zero or more double-backslashes
( $magic_alternation ) # any magic punctuation variable
}xsm;
}
1;
__END__
#-----------------------------------------------------------------------------
=pod
=head1 NAME
Perl::Critic::Policy::Variables::ProhibitPunctuationVars - Write C<$EVAL_ERROR> instead of C<$@>.
=head1 AFFILIATION
This Policy is part of the core L<Perl::Critic|Perl::Critic>
distribution.
=head1 DESCRIPTION
Perl's vocabulary of punctuation variables such as C<$!>, C<$.>, and
C<$^> are perhaps the leading cause of its reputation as inscrutable
line noise. The simple alternative is to use the L<English|English>
module to give them clear names.
$| = undef; #not ok
use English qw(-no_match_vars);
local $OUTPUT_AUTOFLUSH = undef; #ok
=head1 CONFIGURATION
The scratch variables C<$_> and C<@_> are very common and are pretty
well understood, so they are exempt from this policy. The same goes
for the less-frequently-used default filehandle C<_> used by stat().
All the regexp capture variables (C<$1>, C<$2>, ...) are exempt too.
C<$]> is exempt because there is no L<English|English> equivalent and
L<Module::CoreList|Module::CoreList> is based upon it.
You can add more exceptions to your configuration. In your
perlcriticrc file, add a block like this:
[Variables::ProhibitPunctuationVars]
allow = $@ $!
The C<allow> property should be a whitespace-delimited list of
punctuation variables.
Other configuration options control the parsing of interpolated
strings in the search for forbidden variables. They have no effect
on detecting punctuation variables outside of interpolated strings.
[Variables::ProhibitPunctuationVars]
string_mode = thorough
The option C<string_mode> controls whether and how interpolated
strings are searched for punctuation variables. Setting
C<string_mode = thorough>, the default, checks for special cases
that may look like punctuation variables but aren't, for example
C<$#foo>, an array index count; C<$$bar>, a scalar dereference; or
C<$::baz>, a global symbol.
Setting C<string_mode = disable> causes all interpolated strings to
be ignored entirely.
Setting C<string_mode = simple> uses a simple regular expression to
find matches. In this mode, the magic variables C<$$>, C<$'>, C<$#>
and C<$:> are ignored within interpolated strings due to the high
risk of false positives. Simple mode is retained from an earlier
draft of the interpolated- strings code. Its use is only recommended
as a workaround if bugs appear in thorough mode.
The C<string_mode> option will go away when the parsing of
interpolated strings is implemented in PPI. See L</CAVEATS> below.
=head1 BUGS
Punctuation variables that confuse PPI's document parsing may not be
detected correctly or at all, and may prevent detection of
subsequent ones. In particular, C<$"> is known to cause difficulties
in interpolated strings.
=head1 CAVEATS
ProhibitPunctuationVars relies exclusively on PPI to find
punctuation variables in code, but does all the parsing itself for
interpolated strings. When, at some point, this functionality is
transferred to PPI, ProhibitPunctuationVars will cease doing the
interpolating and the C<string_mode> option will go away.
=head1 AUTHOR
Jeffrey Ryan Thalhammer <thaljef@cpan.org>
=head1 COPYRIGHT
Copyright (c) 2005-2009 Jeffrey Ryan Thalhammer. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. The full text of this license
can be found in the LICENSE file included with this module.
=cut
# Local Variables:
# mode: cperl
# cperl-indent-level: 4
# fill-column: 78
# indent-tabs-mode: nil
# c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :