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!
As @hek2mgl comments above, a flexible way of doing that is using a shell wrapper, since the shebang admits a single argument (which is going to be perl). A simple wraper would be this one
#!/bin/bash
env perl -d:Trace "$@"
Which you can use then like this
#!./perltrace
or you can create similar scripts, and put them wherever perl resides.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With