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.
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.
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.
Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.
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.
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
my ($relpath) = $abspath =~ m#/var/ftp/(.*)$#;
In list context the match returns the values of the groups.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With