Perl qr // operation

I have a question about Perl qr operator:

#!/usr/bin/perl -w &mysplit("a:b:c", /:/); sub mysplit { my($str, $pattern) = @_; my @arr = split $pattern, $str; print "@arr\n"; } 

Result:

Using the uninitialized value of $ _ according to the pattern (m //) in the string. /test.pl 3.
Using the uninitialized value of $ pattern in compiling regexp in a string. /test.pl 7.

But when I used: &mysplit("a:b:c", qr/:/); , this is normal.
So I want to know what is the difference between qr// and m// ?
Why is $_ here?
And why is this normal in the case of split /:/, "a:b:c"; ?

Thank you in advance!

+4
source share
2 answers

Well, your problem here is that this expression:

 /:/ 

really means the following:

 $_ =~ /:/ 

This is why perl reports an uninitialized error on $_ .

The qr() operator does not have this label, therefore, is itself an acceptable statement in this case.

So, to be clear: your statement:

 &mysplit("a:b:c", /:/); 

This actually means:

 &mysplit("a:b:c", $_ =~ /:/); 

Since $_ undefined, regex matching returns an empty list. It could return an empty string, but since you have a list context, it returns an empty list, making the error somewhat more obvious.

Since it returns an empty list, only one argument is passed to mysplit() , so you get a second warning:

 Use of uninitialized value $pattern in regexp compilation at ./test.pl line 7. 

If an empty line was passed, this part of the error would be silent.

In addition, you should be aware that using ampersand & before subroutine calls has a specific function. You should not use it if you are not going to use this function. The various ways to call sub are as described in perldoc perlsub :

 NAME(LIST); # & is optional with parentheses. NAME LIST; # Parentheses optional if predeclared/imported. &NAME(LIST); # Circumvent prototypes. &NAME; # Makes current @_ visible to called subroutine. 

By default, the top one is used, in your case: mysplit(...)

+11
source

This error:

 Use of uninitialized value $pattern in regexp compilation at ./test.pl line 7. 

This is because you do not quote the second parameter

 &mysplit("a:b:c", /:/); 

If you tried to print $pattern in sub mysplit , you will see that it is an empty string.

0
source

Source: https://habr.com/ru/post/1483539/


All Articles