user2817749 user2817749 - 1 year ago 57
Perl Question

What is this backtick at the beginning of a directory name? (perl)

I am trying to understand a program. Correct my if I'm wrong, but backticks are used to execute commands in a shell, so I'm not sure what it is its purpose in the following code:

my $end = $` if $dir =~ m/\/foldername/;
foreach my $folder (@dirs_) {
my $start_from = "$dir" . "\/" . "$folder";
my $move_to = "$end" . "\/" . "$folder";
rmtree $move_to;
dircopy($start_from, $move_to);


It's not very pretty is it.

The $` variable is one of the trinity $`, $& and $' which represent the pre-match, match, and post-match parts of the last string that was subjected to a successful regex comparison

For instance, if I have

my $s = 'abcdef';

then after

$s =~ /c./;

you will find that $` is ab, $& is cd, and $' is ef

It's important to remember that, just like the capture variables $1, $2 etc., these three are unaffected by failed regex matches. It's vital to check whether a regex pattern matched before using any of them

This is archaic Perl, maintained primarily for backward compatability. It was a good idea at the time because Perl was keeping close to shell syntax (as were awk and sed, which still do). Nowadays it is best to use regex captures, or perhaps the new @- and @+ arrays

All of the special built-in variables are documented in perldoc perlvar