Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 448
user13107 Avatar asked Dec 10 '22 06:12

user13107


2 Answers

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!

like image 114
mwp Avatar answered Jan 06 '23 14:01

mwp


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.

like image 30
jjmerelo Avatar answered Jan 06 '23 14:01

jjmerelo