Sridhar-Sarnobat Sridhar-Sarnobat - 1 year ago 59
Perl Question

Execute module-qualified function inside perl regex substitution?

I have the following perl one-liner to convert


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

but I'm missing something in my invocation of
, 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
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


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'