perlqx

How to use __FILE__ inside qx?


I'm trying to assign a constant at the top of a Perl script like so:

use constant {
  # ...
  CONSTNAME => qx{readlink -e __FILE__} || __FILE__,
  # ...
};

__FILE__ does not get interpolated inside the qx operator, which causes this to fail. How can I achieve what I want, which is to interpolate the __FILE__ before calling readlink of the shell.

Please note: it is not an option to store the command inside an intermediate variable in between.


Solution

  • To answer the question directly, you can use the interpolate-arbitrary-expression-in-string idiom described in perlref:

    print qx{echo @{[ __FILE__ ]}};
    

    A couple caveats raised in the comments:

    If your goal is to find the path of your perl script with all symlinks resolved, you may want to look at the FindBin module. FindBin has been part of the core perl distribution for some time (at least since 5.004 according to http://search.cpan.org/~chips/perl5.004/).