can somebody explain this weird behavior:
I hava path in a string and I want to split it for each backslash
my $path = "D:\Folder\AnotherFolder\file.txt";
my @folders = split('\', $path);
in the case above it won't work not even if escaping the backslash like this:
my @folders = split('\\', $path);
but in the case of a regexp it will work:
my @folders = split( /\\/, $path);
why is so?
I think amon
gave the best literal answer to your question in his comment:
more explicitly: strings and regexes have different rules for escaping. If a string is used in place of a regex, the string literals suffer from double escaping
Meaning that split '\\'
uses a string and split /\\/
uses a regex.
As a practical answer, I wanted to add this:
Perhaps you should consider using a module suited for splitting paths. File::Spec
is a core module in Perl 5. And also, you have to escape backslash in a double quoted string, which you have not done. You can also use single quotes, which looks a bit better in my opinion.
use strict;
use warnings;
use Data::Dumper;
use File::Spec;
my $path = 'D:\Folder\AnotherFolder\file.txt'; # note the single quotes
my @elements = File::Spec->splitdir($path);
print Dumper \@elements;
Output:
$VAR1 = [
'D:',
'Folder',
'AnotherFolder',
'file.txt'
];
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