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

Is there any way to use the "do" command like I would use "source" in bash shell programming without stopping the use of "warnings" and "strict"?

More often, I find myself thinking of file names, and writing functions and defining variables in those, according to my own naming procedures. That's why I like using code from other files.

For example:

file1: paths.pl

our $path1 = "/path/one";

file2: program.pl

#!/usr/bin/perl # use warnings; # use strict; do 'paths.pl'; print $path1."\n";
-Max

Replies are listed 'Best First'.
Re: "do" command versus "source" in bash
by hippo (Archbishop) on Jan 25, 2024 at 13:50 UTC
    That's why I like using code from other files.

    Code reuse is a Good Thing. The way this is usually done in Perl is with modules.

    TIMTOWTDI but one example using Exporter is shown here to get you started. Here is a module MyPaths.pm which I have just written:

    use strict; use warnings; package MyPaths; use parent 'Exporter'; our @EXPORT_OK = qw/$pathfoo $pathbar/; our $pathfoo = '/path/foo'; our $pathbar = '/otherpath/bar'; 1;

    And here is importtest.pl which makes use of that module:

    #!/usr/bin/env perl use strict; use warnings; use lib '.'; use MyPaths '/path/'; print "paths are $pathfoo and $pathbar\n";

    The use statement will import any exportable symbols from the module which match the regular expression. When we run importtest.pl we see this:

    $ ./importtest.pl paths are /path/foo and /otherpath/bar $

    There is a lot more to modules and exporting/importing than this but it shows you how to get going with the basics.


    🦛

Re: "do" command versus "source" in bash
by shmem (Chancellor) on Jan 25, 2024 at 12:29 UTC

    Of course. Just define your variable in the invoking program as well:

    #!/usr/bin/perl use warnings; use strict; our $path1; do './paths.pl'; # you have to use ./, since '.' is no longer in @INC print $path1."\n";
    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'