I am trying to parse the filename from paths. I have this:
my $filepath = "/Users/Eric/Documents/foldername/filename.pdf";
$filepath =~ m/^.*\\(.*[.].*)$/;
print "Linux path:";
print $1 . "\n\n";
print "-------\n";
my $filepath = "c:\\Windows\eric\filename.pdf";
$filepath =~ m/^.*\\(.*[.].*)$/;
print "Windows path:";
print $1 . "\n\n";
print "-------\n";
my $filepath = "filename.pdf";
$filepath =~ m/^.*\\(.*[.].*)$/;
print "Without path:";
print $1 . "\n\n";
print "-------\n";
But that returns:
Linux path:
-------
Windows path:Windowsic
ilename.pdf
-------
Without path:Windowsic
ilename.pdf
-------
I am expecting this:
Linux path:
filename.pdf
-------
Windows path:
filename.pdf
-------
Without path:
filename.pdf
-------
Can somebody please point out what I am doing wrong?
Thanks! 🙂
Well, the answer to what is happening would be: various errors.
$filepathdoesn’t have any\\s in it, so it won’t match and there’s no$1. You put/s in it. Your expression would have to be:You’re using double quotes, which, taking their cue from UNIX shells, are more active than single quote strings. Thus, you need to escape all your backslashes, like this:
or just use single quotes:
Actually, since perl understands
'/'for windows, this works too (but not for the regex.)As long as you fix it before handing it back to Windows.
This didn’t match, so
$1is still the last match. That’s why it’s repeated. But this points up the value of catching the captures instead of referring to$1.