Split by dots using Perl

I used the split function in two ways. First way:

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

I get this error: Use of uninitialized value in print

When I split into the second method, I had no mistake.

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

My first way of splitting doesn't work just for the point.

Can someone explain the reason for this to me?

+4
source share
3 answers

"\." simple . , carefully with escape sequences.

If you need a backslash and a dot in a line with two quotes, you need "\\." . Or use single quotes: '\.'

+9
source

if you just want to parse files and get their suffixes, it is better to use the fileparse() method from File::Basename

+6
source

Additional information to the information provided by @Mat:

In split "\.", ... first split parameter is first interpreted as a double-quoted string before passing it to the regex engine. As Mat said inside a line with two quotes, and \ is an escape character meaning "take the next character literally", for example. for things like double quotes inside a string with two quotes: "\""

So your split gets a "." like a template. A single dot means "division into any character." As you know, the split itself is not part of the results. Thus, as a result, there are several blank lines.

But why is the first element undefined instead of empty? The answer lies in the documentation for split : if you do not 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. Since all elements are empty, the list is empty, so the first element does not exist and is undefined.

You can see the difference with this particular fragment:

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

It outputs 0 6 .

The β€œright” way to handle this, however, is what @ soulSurfer2010 said in a post.

+3
source

All Articles