But just as a point of interest, you have two alternatives: a regex-only solution would be simplyuse File::Spec::Functions qw(canonpath splitdir); my (@path) = splitdir canonpath $path; # @path now contains ('', 'home', 'a', 'ff.pl') print $path[2], "\n";
This will match a string that starts with /home/, followed by at least one character that is not a slash, and will capture all these non-slash characters. The other way would be to split on slashes:my ($userhome) = ($path =~ m!^/home/([^/]+)!);
my @path = split m!/!, $path; # @path is now ('', 'home', 'a', 'ff.pl') print $path[2], "\n";
Note how I used $path instead of your $a. This is for two reasons - first of all, $a and $b carry a special meaning for the sort function in Perl, so you shouldn't use them elsewhere. And secondly, $a is not very descriptive. Variables and functions should always have descriptive names, lest you find yourself boggling at your own code after putting it aside for two weeks.
Also note how I used m!! instead of // to delimit the regular expressions. If you explicitly mention the m, Perl allows you to pick something other than forward slashes as delimiters, so you won't need to backwhack forward slashes inside the pattern. This is very handy to avoid "leaning toothpick syndrome". This and more is described in perldoc perlop.
Makeshifts last the longest.
In reply to Re: Matching part of a path
by Aristotle
in thread Matching part of a path
by hweefarn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |