开发者

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.


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

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


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


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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜