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

Hi How can I source a script in to a perl program? This script can be C program or Korn Shell script or a perl module. In korn shell we can simply do . <script_name> Is there any similar functionality? Sarath

Replies are listed 'Best First'.
Re: source a program
by etcshadow (Priest) on Nov 19, 2004 at 03:53 UTC
    The nearest perl equivalent to "sourcing" in shell is do. In shell, "sourcing" is different from executing... that is: when you execute a program (whether another shell script or a binary executable or whatever) it executes in a separate process, with it's own environment and variables and so on. When you source another shell script (you can only source other shell scripts, you cannot source a binary executable) it is just treated as though the code were dropped right into your shell (or shell script) right there. Thus, any changes to the shell's environment and variables and so on which are made by the source-ee take effect in the source-or (big difference from when another command is executed in a subprocess/subshell).

    Anyways, likewise in perl. You can execute any arbitrary command (a shell script, perl script, binary executable, whatever... see perldoc -f system), but it will occur in its own subprocess. You can also "source" a file full of other perl code directly into your perl script, affecting your scripts environment, variables, and so on. You do that like:

    do "script_name.pl";
    just like you would say:
    source script_name.sh
    or (the same thing)
    . script_name.sh
    (the . is just a shortcut for writing the command "source" in shell). There are some minor differences between perl's "do" and shell's "source". The biggest difference is probably that perl's "do" will return the last value computed in the called script. For more info, check out perldoc -f do.
    ------------ :Wq Not an editor command: Wq
Re: source a program
by data64 (Chaplain) on Nov 19, 2004 at 04:22 UTC
Re: source a program
by Errto (Vicar) on Nov 19, 2004 at 03:19 UTC

    From within Perl, you can execute any other command with the backtick operator. So my $foo = `foo` will execute the program "foo" and return anything it wrote in its standard output into the variable $foo. However, all such commands execute in a sub-process. In other words, if the program `foo` changes the current directory or sets some environment variables, this will not be reflected when Perl resumes execution (unlike when sourcing one shell script within another). In Perl you use the global hash %ENV to set environment variables and the chdir() builtin to change directories.

    You should not, however, use this technique to load Perl modules. Instead you should use the use declaration. See the Simple Module Tutorial in Tutorials.