tel2 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm using Perl 5.10.1 on Linux and if I run this code:

#!/usr/bin/perl #...miscellaneous code here... require MIME::Base64; $x = encode_base64('abc');
it fails with this error: "Undefined subroutine &main::encode_base64 called at ./test.pl line 4."

Changing the "require" to "use" avoids the error.

Why do I get the above error when I "require", but not when I "use"?

(I was wanting to use "require" because this part of the code is rarely executed, so I thought this would be (slightly) more efficient.)

Thanks.
Tel2

Replies are listed 'Best First'.
Re: "require MIME::Base64" vs "use..."
by stevieb (Canon) on Jul 07, 2015 at 02:45 UTC

    Try:

    require MIME::Base64; import MIME::Base64; $x = encode_base64('abc');

    use implies both require and import, so see if that fixes the issue.

    EDIT: For those future readers, the reason why its a performance benefit in certain cases to require and import instead of use is because use is run at compile time, so no matter where you use a module, it's loaded permanently throughout the entire run of your process.

    Conversely, require loads a module at runtime, and once the scope it is used in ends, the module is unloaded. Therefore, for parts of your program that are rarely called that need specific modules, it's often preferable to require them for their short lives and reduce the memory footprint of your application.

    -stevieb

      Yes, that works thanks stevieb!

      So "require" was insufficient by itself because I was trying to access one of the functions of MIME::Base64, but that function hadn't been imported, right?

        Yes, and you could have used it anyway if you called it by its full package name:

        #!/usr/bin/env perl use strict; use warnings; use 5.010; require MIME::Base64; my $x = MIME::Base64::encode_base64('abc'); say $x;
        $ perl 1133493.pl $ YWJj $

        Note the extra new line ... you will probably want to chomp what you get back from encode_base64 ....

        Remember: Ne dederis in spiritu molere illegitimi!
Re: "require MIME::Base64" vs "use..."
by Anonymous Monk on Jul 07, 2015 at 02:43 UTC
      Thanks for that, Anonymous Monk!