Sridhar-Sarnobat Sridhar-Sarnobat - 11 months ago 55
Perl Question

Execute module-qualified function inside perl regex substitution?

I have the following perl one-liner to convert

/path/to/file.txt
to
/path/to/


echo "/path/to/file.txt" | perl -pe 's{(.*)}{File::Basename->dirname($1)}ge'


but I'm missing something in my invocation of
File::Basename->dirname()
, causing the following error:

Can't locate object method "dirname" via package "File::Basename" (perhaps you forgot to load "File::Basename"?) at -e line 1, <> line 1.


What am I missing?

(I know I can just use
dirname
from bash but I'm trying to do something more complicated with perl than what this stripped down example shows).

Answer Source

The problem was that you had <button> in the replacement string, but you've removed that now so it should work

The replacement string must be a valid Perl expression if you're using the /e modifier, and

<button>File::Basename->dirname($1)

isn't valid Perl


The correct command would be:

echo "/path/to/file.txt" | perl -pe 'use File::Basename 'dirname'; s{([^\n]+)}{dirname($1)}ge'