Saket Khandelwal
Saket Khandelwal

Reputation: 347

perl script not extracting only path (regex)

I have this regex expression

($oldpath = $_) =~ m/^\/(.+\/)*/;

This is the input:

/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/110-lafayette_railroad.mp3

But the output is:

/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/110-lafayette_railroad.mp3

When it should be:

/cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/

Thanks in advance. :)

Upvotes: 0

Views: 37

Answers (1)

choroba
choroba

Reputation: 242383

What do you mean by "output"? $1 contains

cd-lib/mp3/rock/LittleFeat/Dixie_Chicken/

which is almost what you wanted (it just misses the leading /).

You assigned $_ to $oldpath, than matched it against a regex. It doesn't change either $_ or $oldpath.

The canonical way is

my ($match) = m/^\/(.+\/)*/;

or rather (to prevent the leaning toothpick syndrome)

my ($match) = m{^/(.+/)*};

i.e. running the match in list context returns the matching capture groups, and the first one is assinged to $match.

Upvotes: 1

Related Questions