简体   繁体   中英

Split by dot using Perl

I use the split function by two ways. First way (string argument to split ):

my $string = "chr1.txt";
my @array1 = split(".", $string);
print $array1[0];

I get this error:

Use of uninitialized value in print

When I do split by the second way (regular expression argument to split ), I don't get any errors.

my @array1 = split(/\./, $string); print $array1[0];

My first way of splitting is not working only for dot.

What is the reason behind this?

"\\." is just . , careful with escape sequences.

If you want a backslash and a dot in a double-quoted string, you need "\\\\." . Or use single quotes: '\\.'

如果您只想解析文件并获取它们的后缀,最好使用File::Basenamefileparse()方法。

Additional details to the information provided by Mat :

In split "\\.", ... the first parameter to split is first interpreted as a double-quoted string before being passed to the regex engine. As Mat said, inside a double-quoted string, a \\ is the escape character, meaning "take the next character literally", eg for things like putting double quotes inside a double-quoted string: "\\""

So your split gets passed "." as the pattern. A single dot means "split on any character". As you know, the split pattern itself is not part of the results. So you have several empty strings as the result.

But why is the first element undefined instead of empty? The answer lies in the documentation for split : if you don't impose a limit on the number of elements returned by split (its third argument) then it will silently remove empty results from the end of the list. As all items are empty the list is empty, hence the first element doesn't exist and is undefined.

You can see the difference with this particular snippet:

 my @p1 = split "\.", "thing";
 my @p2 = split "\.", "thing", -1;
 print scalar(@p1), ' ', scalar(@p2), "\n";

It outputs 0 6 .

The "proper" way to deal with this, however, is what @soulSurfer2010 said in his post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM