in reply to Re^5: pass perl variable to shell script
in thread pass perl variable to shell script

OK, so you are saying that in order for me to get access to a variable that was set in perl block, I woud need to print that variable either to stdout or to a file and then read it back in the shell part of the code? Since I don't want to print into a file, then I need to print to stdout. But when morgon says:
variable=$(perl script.pl)
what is 'script.pl'? I don't have a .pl script. I only have .sh script.

Replies are listed 'Best First'.
Re^7: pass perl variable to shell script
by morgon (Priest) on Aug 11, 2010 at 21:11 UTC
    You cannot simply reference a Perl-variable in a shell-script.

    You have to find a way to pass the *value* of the variable from Perl to the shell.

    The way via command-subsitution I showed above is one way to do this.

    Perl prints the value to STDOUT and the shell reads it into a shell-variable (which is different from the perl-variable).

    Now if you have the perl-script directly embedded in your shell-script as a here-doc then you will have all sorts of problems properly escaping stuff, which is why I suggested above that you put all the Perl-code into a script of it's own that you can call anything you like - I called it simply "script.pl" for illustration but what you have to do is to move the perl-code from the shell-script into a perl-script file and call that file via command-substitution.

      That's the most logical answer, and I'd stick to that for all but exceptional circumstances. The two alternative ways to do it that I know of are:
      - maybe still possible to use perl + c code to do what I did years ago in C alone: look up the memory location of a system level variable and change it directly. not recommended.
      - in unix/linux most shells you can use backticks to evaluate (possibly nested) calls to programs or regexes etc. and receive the value during a particular evaluation nest level, to set a shell variable for instance, e.g.
      set str3=`perl my_whatever_perl_script.pl` export str3
      depends which shell as to what exact syntax, but the backticks should work. your perl script should return as an exit value the value you want assigned to the shell variable.
      the second alternative is quite usable in situations where it's absolutely necessary.
      the hardest line to type correctly is: stty erase ^H