avances123
avances123

Reputation: 2344

How do I assign the result of a regex match to a new variable, in a single line?

I want to match and assign to a variable in just one line:

my $abspath='/var/ftp/path/to/file.txt';

$abspath =~ #/var/ftp/(.*)$#;
my $relpath=$1;

I'm sure it must be easy.

Upvotes: 11

Views: 14227

Answers (5)

Francisco R
Francisco R

Reputation: 4048

You can accomplish it with the match and replace operator:

(my $relpath = $abspath ) =~ s#/var/ftp/(.*)#$1# ;

This code assigns $abspath to $relpath and then applies the regex on it.

Edit: Qtax answer is more elegant if you just need simple matches. If you ever need complex substitutions (as I usually need), just use my expression.

Upvotes: 9

mirod
mirod

Reputation: 16161

With Perl 5.14 you can also use the /r (non destructive substitution) modifier:

perl -E'my $abspath="/var/ftp/path/to/file.txt"; \
        my $relpath= $abspath=~ s{/var/ftp/}{}r; \
        say "abspath: $abspath - relpath: $relpath"'

See "New Features of Perl 5.14: Non-destructive Substitution" for more examples.

Upvotes: 5

dolmen
dolmen

Reputation: 8706

As you just want to remove the beginning of the string you could optimize the expression:

(my $relpath = $abspath) =~ s#^/var/ftp/##;

Or even:

my $relpath = substr($abspath, 9);

Upvotes: 0

daxim
daxim

Reputation: 39158

Obligatory Clippy: "Hi! I see you are doing path manipulation in Perl. Do you want to use Path::Class instead?"

use Path::Class qw(file);
my $abspath = file '/var/ftp/path/to/file.txt';
my $relpath = $abspath->relative('/var/ftp');
# returns "path/to/file.txt" in string context

Upvotes: 18

Qtax
Qtax

Reputation: 33918

my ($relpath) = $abspath =~ m#/var/ftp/(.*)$#;

In list context the match returns the values of the groups.

Upvotes: 18

Related Questions