Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I "use warnings" only in one subroutine?

Tags:

warnings

cgi

perl

I’m working on a Perl CGI script about 4000 lines big. Our coding style includes use strict and use warnings usually, but in this particular (quite old) file, "use warnings" is commented out, with the comment stating that enabling warnings would flood the Apache log.

Now I plan to separate some code into a new subroutine. I want to use warnings at least there. How can I safely limit the effect of use warnings to one subroutine? Will just placing the use clause inside the subroutine do the job?

like image 346
Stefan Majewsky Avatar asked Nov 27 '22 22:11

Stefan Majewsky


1 Answers

Yes, the use of use warning will be in the scope in which you have written it.

Writing use warning inside a sub will only affect the giving routine (or block).


example snippet

sub foo {
  use warnings;
  print  my $a; 
}

{
  use warnings;
  print  my $b;
}

foo;

print my $c;

output

Use of uninitialized value $b in print at foo.pl line 8.
Use of uninitialized value $a in print at foo.pl line 3.

Note that no warning is thrown about the use of print my $c.


What does the documentation say?

  • perldoc.perllexwarn

    This pragma works just like the strict pragma. This means that the scope of the warning pragma is limited to the enclosing block. It also means that the pragma setting will not leak across files (via use, require or do). This allows authors to independently define the degree of warning checks that will be applied to their module.

like image 157
Filip Roséen - refp Avatar answered Dec 05 '22 07:12

Filip Roséen - refp