understanding perl behaviour when loading a module using use keyword within if block

StackOverflow https://stackoverflow.com/questions/23613800

  •  20-07-2023
  •  | 
  •  

Question

Until now I assumed that use keyword loads the module during compile time and require loads the module during runtime. If that's true then loading a module ( using use ) within a if block, should fail as the block gets executed during runtime!

But I tried testing this using the below code. And the output tells me I am wrong.

#!/usr/bin/perl
my $file = '/home/chidori/dummy.txt';

if ( $file ) {
  use File::Basename;
  my $base_filename = basename($file);
  print "File basename is $base_filename\n";
}

else {
  print "Nothing to display\n";
}

Output

chidori@ubuntu:~$ ./moduletest.pl
File basename is dummy.txt
Was it helpful?

Solution

This behavior is implicitly documented in the POD for use.

Because "use" takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a "use" inside the false branch of a conditional doesn't prevent it from being processed.

The use statment is part of the parse tree of your code. It is executed during the compile phase of perl. The Perl compile won't add the use statement to the parse tree. This means that it won't be executed during the run time of the program.

If you are really curious how the code is parsed, then you can inspect the parse tree with B::Deparse.

OTHER TIPS

use Foo;

is basically the same thing as

BEGIN {
   require Foo;
   import Foo;
}

It gets executed as soon as it's compiled, not when the program is eventually run. As such, it's not subject to conditionals and loops.

It doesn't make much sense to place use File::Basename; inside a block, but it does make sense for other uses of BEGIN and use. It makes sense for lexical pragmas, for example.

use warnings;  # Changes compiler settings.
$x;            # Warns.

{
   no warnings;  # Changes compiler settings.
   $x;           # Doesn't warn.

   {
      use warnings;  # Changes compiler settings.
      $x;            # Warns.
   }

   $x;  # Doesn't warn.
}

$x;  # Warns.
1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top