Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

perl

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.

like image 551
avances123 Avatar asked Jun 08 '11 11:06

avances123


People also ask

What does regex match return?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

Can you return a string in regex?

The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

What does %s mean in Perl?

Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.

How do I search for a pattern in Perl?

Use of Wild Cards in Regular Expression: Perl allows to search for a specific set of words or the words that follow a specific pattern in the given file with the use of Wild cards in Regular Expression. Wild cards are 'dots' placed within the regex along with the required word to be searched.


2 Answers

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
like image 79
daxim Avatar answered Nov 13 '22 01:11

daxim


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

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

like image 21
Qtax Avatar answered Nov 13 '22 01:11

Qtax