How to use /usr/bin/env perl functionality along with perl arguments?

  • A+
Category:Languages

I have a perl script with shebang as

#!/usr/bin/env perl 

I want this script to print each line as it is executed. So I installed Devel::Trace and changed script shebang to

#!/usr/bin/env perl -d:Trace 

But this gives error as it is not a valid syntax.

What should I do to use both env functionality and tracing functionality?


This is one of those things that Just Doesn't Work™ on some systems, notably those with a GNU env.

Here's a sneaky workaround mentioned in perlrun that I've (ab)used in the past:

#!/bin/sh #! -*-perl-*- eval 'exec perl -x -wS $0 ${1+"$@"}'   if 0;  print "Hello, world!/n"; 

This will find perl on your PATH and you can add whatever other switches you'd like to the command line. You can even set environment variables, etc. before perl is invoked. The general idea is that sh runs the eval, but perl doesn't, and the extra gnarly bits ensure that Perl finds your program correctly and passes along all the arguments.

#!/bin/sh FOO=bar; export FOO  #! -*-perl-*- eval 'exec perl -d:Trace -x -wS $0 ${1+"$@"}'   if 0;  $Devel::Trace::TRACE = 1;  print "Hello, $ENV{FOO}!/n"; 

If you save the file with a .pl extension, your editor should detect the correct file syntax, but the initial shebang might throw it off. The other caveat is that if the Perl part of the script throws an error, the line number(s) might be off.

The neat thing about this trick is that it works for Ruby too (and possibly some other languages like Python, with additional modifications):

#!/bin/sh #! -*-ruby-*- eval 'exec ruby -x -wS $0 ${1+"$@"}' /   if false  puts "Hello, world!" 

Hope that helps!

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: