PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

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

 August 19, 2022     environment-variables, linux, perl, trace     No comments   

Issue

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?


Solution

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!



Answered By - mwp
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing