Perl - Cannot get command line arguments in without explicitly putting "perl" before script call [duplicate] - perl

This question already has answers here:
#ARGV is empty using ActivePerl in Windows 7
(4 answers)
Closed 9 months ago.
I'm running ActivePerl 5.8.8 build 822 on Win7 x64. We're working on a project that is about 60% C++, 15% perl, etc. The Perl is heavily used to link bits and pieces and various small utility applications together to create and pack our final data. So, for example, our VS2005 solution has post build events to create hard links to DLL's using a post build perl script which lives at some location on our development drive (it is part of PATH env var).
I found out quickly, that without explicitly putting "perl" to call the interpreter in-front of the postbuild.pl script call, it wouldn't accept command line arguments. I tested this further simply by going to the cmd window and doing the same with a "hello world" style perl script. No command line arguments were passed in when I say "bleh.pl arg1 arg2". But when I say "perl bleh.pl arg1 arg2" I get command line arguments.
When this failure occurs, perl reads zero command line arguments, and the #ARGV variable empty or null (whatever this crazy language does). So they're simply not passed in.
This is an issue because there are hundreds if not thousands of calls to perl scripts which I fear are not behaving correctly, and it is unreasonable to think I should have to prefix every .pl script invocation with perl explicitly, not to mention we're using version control and I don't want to commit all these garbage changes nor manage them in my stash.
PERL env var exists and points at the folder where the perl binary lives. As well as PATHEXT has .PL in it for perl scripts. Likewise, my PATH contains the folder entries to get to the scripts and to perl also.
Any help on how to figure this out would be immensely appreciated! Also, when I installed ActivePerl (I've done so many times now trying to figure this out). I allowed it to change my Path and associate file extensions in windows, which you would think would be the solution.
Thank you!

Your association is broken (incomplete). First, open a console and execute
assoc .pl
You'll get something like
.pl=SOMETHING
Then, execute
ftype SOMETHING
You should get something like
SOMETHING="C:\SOMEWHERE\bin\perl.exe" "%1" %*
but you'll get something like the following instead:
SOMETHING="C:\SOMEWHERE\bin\perl.exe" "%1"
To fix it, execute
ftype SOMETHING="C:\SOMEWHERE\bin\perl.exe" "%1" %*

Related

Series of Perl Scripts. BASH, BATCH, Shell?

I have a series of perl scripts that I want to run one after another on a unix system. What type of file would this be / could I reference it as in documentation? BASH, BATCH, Shell Script File?
Any help would be appreciated.
Simply put the commands you would use to run them manually in a file (say, perlScripts.sh):
#!/bin/sh
perl script1.pl
perl script2.pl
perl script3.pl
Then from the command line:
$ sh perlScripts.sh
Consider using Perl itself to run all of the scripts. If the scripts don't take command line arguments, you can simply use:
do 'script1.pl';
do 'script2.pl';
etc.
do 'file_name' basically copies the file's code into the current script and executes it. It gives each file its own scope, however, so variables won't clash.
This approach is more efficient, because it starts only one instance of the Perl interpreter. It will also avoid repeated loading of modules.
If you do need to pass arguments or capture the output, you can still do it in a Perl file with backquotes or system:
my $output = `script3.pl file1.txt`; #If the output is needed.
system("script3.pl","file1.txt"); #If the output is not needed.
This is similar to using a shell script. However, it is cross-platform compatible. It means your scripts only rely on Perl being present, and no other external programs. And it allows you to easily add functionality to the calling script.

Passing arguments to script, getting: "Use of uninitialized value $ARGV[0]"

Problem: Windows XP is not passing command line arguments to perl scripts.
Symptom: a simple command like:
say "Argument 1 (\$ARGV[0]) is: $ARGV[0], argument 2 (\$ARGV[1]) is: $ARGV[1].";
Resulted in:
Use of uninitialized value $ARGV[0] in concatenation (.) or string at...
Solution:
The root problem is in Windows XP. The default method for starting perl passes only the first variable, which is the script name. Result is that $ARGV[0] is uninitialized.
The fix is to edit the Windows registry at:
\HKEY_CLASSES_ROOT\Perl\shell\Open\command
And make the entry:
"C:\Perl\bin\perl.exe" %*
Result is:
C:\whatever>perl argtest.pl 1 2
Argument 1 ($ARGV[0]) is: 1, argument 2 ($ARGV[1]) is: 2.
Thanks especially to David W who pointed me in the right direction.
Note that #ARGV in Perl is not quite like argv in C.
C Perl
Name of the program argv[0] $0
1st argument argv[1] $ARGV[0]
2nd argument argv[2] $ARGV[1]
n-th argument argv[n] $ARGV[n-1]
So if you provide one command line arguments to a Perl script, it will be found in $ARGV[0]. $ARGV[1] will be uninitialized.
Download Cygwin and test your code in the Cygwin environment. I bet this is a Windows issue. (If you're a Unix head, you'll like Cygwin because it gives you the Unix/Linux like environment on your Windows machine. I don't use Windows without it.)
Windows uses suffixes to determine what program opens what files. Is your Perl script called argtest, argtest.bat or argtest.pl?
On Windows, make sure all of your Perl scripts use the *.pl suffix, so Windows will use whatever Perl parameter to execute them. Windows doesn't use the shebang.
Another possible issue: On Windows XP, I had a problem with Perl scripts with parameters because Windows had this as an execution string:
perl %1
which would execute the Perl program with my script, but ignore the parameters. I had to change this to:
perl %*
Unfortunately, Windows Vista through Windows 8 changed the way this is set. However, I have Windows 7 and don't have this issue. I did make sure to install Perl under C:\Perl and not C:\Program Files\Perl because of the space in the directory name. I also have Strawberry Perl installed.
There is a special Windows environment variable called PATHEXT. This allows you to type in foo instead of foo.pl. If Windows can't see how to execute your file, Windows goes through %PATHEXT and tries appending various suffixes until it finds one that works. You might want to append .PL to that environment variable, so you can type in foo instead of foo.pl all the time.
There are two ways that Windows knows it is supposed to use Perl to execute a program.
The command line begins with the perl executable and the name of the script to be run is provided as a command line argument. This is how it works on Unix and other environments, too.
Your system associates one or more extensions, such as .pl, .pm, and/or .cgi with the Perl application, and Windows will launch Perl when you type a filename with one of those extensions or click on a file with one of those extensions in the Windows explorer.
You have invoked your script simply as
argtest 1 2
and not one of
perl argtest 1 2
argtest.pl 1 2
That makes me think that Perl is not the first application that gets to look at the file referred to by argtest. Perhaps there is a file called argtest.bat or argtest.exe which has the task of getting Perl to run your Perl code. For some reason this intermediate program is not passing the command line arguments that you provide on to the Perl application.
Provide the code for this intermediate file and we can help some more.
UPDATE: David W proposes a 3rd way -- setting the PATHEXT environment variable to inclue .pl files and invoking argtest from the command-line -- see his answer.
Then if Window's file association with the .pl extension was messed up, say, set as just C:\Dwimperl\perl\bin\perl" and not "C:\Dwimperl\perl\binperl %*" then the OP would get the behavior that he describes.
In perl file name is not part of the array of arguments. At least in the test I did you must remove ARGV[2] or pass three arguments, like argtest 1 2 3

How can I find out what script, program, or shell executed my Perl script?

How would I determine what script, program, or shell executed my Perl script?
Example: I might want to have human readable output if executed from shell (customized for each type of shell), a different type of output if called as a script from another perl script, and a machine readable format if executed from a program such as a continuous integration server.
Motivation: I have a tool that changes its output based on which shell executes it. I'd normally implement this behavior as an option to the script, but this tool's design doesn't allow for options. Other shells have environment variables that indicate what shell is running. I'm working on a patch to support Powershell, which has no such special variable.
Edit: Many of these answers happen to be linux specific. Unfortuantely, Powershell is for Windows. getppid, the $ENV{SHELL} variable, and shelling out to ps won't help in this case. This script needs to run cross-platform.
You use getppid(). Take this snippet in child.pl:
my $ppid = getppid();
system("ps --no-headers $ppid");
If you run it from the command line, system will show bash or similar (among other things). Execute it with system("perl child.pl"); in another script, e.g. parent.pl, and you will see that perl parent.pl executed it.
To capture just the name of the process with arguments (thanks to ikegami for the correct ps syntax):
my $ppid = getppid();
my $ps = `ps --no-headers -o cmd $ppid`;
chomp $ps;
EDIT: An alternative to this approach, might be to create soft links to your script, make the different contexts use different links to access your script and inspect $0 to build logic around that.
I would suggest a different approach to accomplish your goal. Instead of guessing at the context, make it more explicit. Each use case is wholly separate, so have three different interfaces.
A function which can be called inside a Perl program. This would likely return a Perl data structure. This is far easier, faster and more reliable than parsing script output. It would also serve as the basis for the scripts.
A script which outputs for the current shell. It can look at $ENV{SHELL} to discover what shell is running. For bonus points, provide a switch to explicitly override.
A script which can be called inside a non-Perl program, such as your continuous integration server, and issue machine readable output. XML and/or JSON or whatever.
2 and 3 would be just thin wrappers to format the data coming out of 1.
Each is tailored to fit its specific need. Each will work without heuristics. Each will be far simpler than trying to guess the context and what the user wants.
If you can't separate 2 and 3, have the continuous integration server set an environment variable and look for it.
Depending on your environment, you may be able to pick it up from the environment variables. Consider the following code:
/usr/bin/perl -MData::Dumper -e 'print Dumper(\%ENV);' | grep sh
On my Ubuntu system, it gets me:
'SHELL' => '/bin/bash',
So I guess that says I'm running perl from a bash shell. If you use something else, the SHELL variable may give you a hint.
But let's say you know you're in bash, but perl is run from a subshell. Then try:
/bin/sh -c "/usr/bin/perl -MData::Dumper -e 'print Dumper(\%ENV);'" | grep sh
You will find:
'_' => '/bin/sh',
'SHELL' => '/bin/bash',
So the shell is still bash, but bash has a variable $_ which also show the absolute filename of the shell or script being executed, which may also give a valuable hint. Similarily, for other environments there will most probably be clues left in the perl %ENV hash that should give you valuable hints.
If you're running PowerShell 2.0 or above (most likely), you can infer the shell as a parent process by examining the environment variable %psmodulepath%. By default, it points to the system modules under %windir%\system32\windowspowershell\v1.0\modules; this is what you would see if you examine the variable from cmd.exe.
However, when PowerShell starts up, it prepends the user's default module search path to this environment variable which looks like: %userprofile%\documents\windowspowershell\modules. This is inherited by child processes. So, your logic would be to test if %psmodulepath% starts with %userprofile% to detect powershell 2.0 or higher. This won't work in PowerShell 1.0 because it does not support modules.
This is on Windows XP with PowerShell v2.0, so take it with a grain of salt.
In a cmd.exe shell, I get:
PSModulePath=C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\
whereas in the PowerShell console window, I get:
PSModulePath=E:\Home\user\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsP
owerShell\v1.0\Modules\
where E:\Home\user is where my "My Documents" folder is. So, one heuristic may be to check if PSModulePath contains a user dependent path.
In addition, in a console window, I get:
!::=::\
in the environment. From the PowerShell ISE, I get:
!::=::\
!C:=C:\Documents and Settings\user

Sourcing shell scripts in Perl

I want to source a shell script from within Perl and have the environment variables be available in Perl, but I'm not sure if there's an elegant way to do it. Obviously, using system() won't work since it runs in a forked process, and all environment changes will be lost. I think there's a CPAN module that can do it, but I prefer not to use external modules.
I've seen two solutions that would not work in my case:
Have a wrapper that calls the shell script, and then calls the Perl script. I do not know ahead of time which of my shell scripts I need to call.
Manually opening the shell script and scraping for arg=value pairs. This won't work either because the shell script is not a simple list of ARG=VALUE, but rather contain a bunch of conditionals, and variables can have different values depending on certain conditions.
sh -c "source script; env" should output the environment at the end of script as name=value pairs, which you then can parse from your perl script (as Perl is a language made for parsing, this should be easy).
You can do this by installing external module from CPAN which is Shell::Source
$env_path= Shell::Source->new(shell=>"tcsh",file=>"../path/to/file/temp.csh");
$env_path->inherit;
As perl creates its own instance while running on a shell, so we can not set environment path for the main shell as the perl's instance will be like sub shell of the main shell. Child can not set environment paths for parents.
Now till the perl's sub shell will run you'll be able to access all the paths present in temp.csh by using Shell::Source

Bash: Chroot command passing 2 string parameters or better run a series of commands

I would like to do something like this:
chroot /mount-point /path/to/script $var1 $var 2
Will this work? Will the chrooted Perl script be passed on these 2 parameters?
If not, how to do this?
Otherwise, is there any way to simply do chroot in the script, and then start doing commands such as
perl script.pl $var1 $var2 etc?
As I understand it, simply writing them sequentially in bash will only get them executed after chroot is finished, and control is returned back to where I don't have perl installed (its a ramdisk running from PXE).
Chroot should handle this just fine. Just make sure that your perl script can find a Perl interpreter from the chroot context, that the Perl executable can find the shared libraries it needs, and that your variables, if they contain paths, have paths relative to the new root, not the old. You may want to compile a statically-linked perl executable, if that's easier for you than making copies of the required shared libraries in the chroot.
Or you can use Expect, which is a scripting language for interacting with input/output.
http://en.wikipedia.org/wiki/Expect