How should the split function work in perl?

Today I had difficulties with the split function and read perlfunc to see if I misinterpreted something. I tried to split the string into ".", Which according to perlfunc should be supported this way:

my $string = "hello.world";
my ($hello, $world) = split(".", $string);

or

my $string = "hello.world";
my ($hello, $world) = split(/\./, $string);

However, testing the first led to empty variables, so I continued testing as follows:

#!/usr/bin/perl

use strict;
use warnings;

my $time_of_test = "13.11.19.11.45.07";
print "TOD: $time_of_test\n";
my ($year, $month, $day, $hr, $min, $sec) = split(/\./, $time_of_test);
print "Test 1 -- Year: $year month: $month day: $day hour: $hr min: $min sec: $sec\n";
($year, $month, $day, $hr, $min, $sec) = split(".", $time_of_test);
print "Test 2 -- Year: $year month: $month day: $day hour: $hr min: $min sec: $sec\n";
($year, $month, $day, $hr, $min, $sec) = split('.', $time_of_test);
print "Test 3 -- Year: $year month: $month day: $day hour: $hr min: $min sec: $sec\n";
($year, $month, $day, $hr, $min, $sec) = split("\.", $time_of_test);
print "Test 4 -- Year: $year month: $month day: $day hour: $hr min: $min sec: $sec\n";
($year, $month, $day, $hr, $min, $sec) = split('\.', $time_of_test);
print "Test 5 -- Year: $year month: $month day: $day hour: $hr min: $min sec: $sec\n";

Here is the result:

> ./test.pl  
TOD: 13.11.19.11.45.07
Test 1 -- Year: 13 month: 11 day: 19 hour: 11 min: 45 sec: 07
Test 2 -- Year:  month:  day:  hour:  min:  sec: 
Test 3 -- Year:  month:  day:  hour:  min:  sec: 
Test 4 -- Year:  month:  day:  hour:  min:  sec: 
Test 5 -- Year: 13 month: 11 day: 19 hour: 11 min: 45 sec: 07

Does this work as intended? If so, how did I misinterpret the perlfunc documentation?

+4
source share
4 answers

- . ( " "), .

, "." '.', , ( ).

/\./ '\.' , .

"\.", escape- , split. , split, , ".".

+9

'\n' \n. '.' .. . . , . \. , '\.' '\\.'. , /\./.

+4

split . '.' " ". , /\./, '.'

0

. , :

my $string = 'hello.world';
my ($hello, $world) = split('\\.', $string);
print "$hello\n";

"".

If you pass only '\.', it will end as just a template '.'in the split function. You need two backslashes, so that it ends as '\.'passed to the split function.

0
source

All Articles