Jerry Jerry - 1 year ago 79
Perl Question

Understanding a code chunk of perl

Can anyone explain to me what the following is trying to do? What is the purpose behind this code chunk?

eval 'exec perl5 -S $0 ${1+"$@"}'
if 0;

Thanks much!

EDIT1: I'm trying to change the code block above into:

eval 'exec perl5 -S $0 ${1+"$@"}'
if 0;

and I think it should work because the script is treated like shell script and
get executed and
is invoked to use perl to execute the same script. However, when I actually run this, I got:

/bin/sh: -S: invalid option

Can anyone explain why this case the script is failed. Do I misunderstand something? I'm using

Thanks much!

EDIT2: EDIT1 seems like a totally separate question and I post it here

Answer Source

This is a dirty trick to get a script file to run either properly, under perl, or if it is submitted directly to the shell

The statement does absolutely nothing under perl because of the if 0 at the end

However, if it's executed by sh or bash then the continuation line will be ignored, and the shell will do the eval, and run the same file through perl5

The idea is that, while Perl considers newlines as just more whitespace, the shell sees them as statement terminators. That means Perl will ignore the eval (as long as it compiles) because the rest of the statement says if 0, while a shell will execute it and exec to a whole new process

I can't say I see the point, because a proper shebang line will allow you to run directly from the command line anyway, but there we are. People like hacks because it makes them feel clever

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download