Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

for my $item (@array) {
    if (index($item, '$n') != -1) {
       print "HELLO
";
    }
} 

Problem is: Perl critic gives below policy violation.

String may require interpolation at line 168, near '$item, '$n''. (Severity: 1)

Please advise how do I fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

In this case the analyzer either found a bug or is plain wrong in flagging your code.

Are you looking for a literal "$n" in $item, or for what $n variable evaluates to?

  • If you want to find the literal $n characters then there is nothing wrong with your code

  • If you expect $item to contain the value stored in $n variable then allow it to be evaluated,

    if (index($item, $n)  != -1)
    

    If this is indeed the case but $n may also contain yet other escaped sequences or encodings which you need as literal characters (so to suppress their evaluation) then you may need to do a bit more, depending of what exactly may be in that variable.

In case you do need to find characters $ followed by n (what would explain a deliberate act of putting single quotes around a variable) you need to handle the warning.

For the particular policy that is violated see Perl::Critic::Policy::ValuesAndExpressions

This policy warns you if you use single-quotes or q// with a string that has unescaped metacharacters that may need interpolation.

To satisfy the policy you'd need to use double quotes and escape the $, for example qq($n). In my opinion this would change the fine original code segment into something strange to look at.

If you end up wanting to simply silence the warning see documentation, in Bending The Rules

A comment. The tool perlcritic is useful but you have to use it right. It's a static code analyzer and it doesn't know what your program is doing, so to say; it can catch bad practices but can't tell you how to write programs. Many of its "policies" are unsuitable for particular code.

The book that it is based on says all this very nicely in its introduction. Use sensibly.


When I look at the question where this comes from it appears that you are looking for index at which substrings were matched, so you need the content of $n variable, not literal "$n". Then perlcritic identified a bug in the code, good return for using it!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...