Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl split interesting behavior

Tags:

split

perl

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?

like image 279
Andrei Doanca Avatar asked Sep 30 '13 12:09

Andrei Doanca


1 Answers

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'
        ];
like image 69
TLP Avatar answered Sep 28 '22 09:09

TLP