Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Funky 'x' usage in perl

Tags:

perl

My usual 'x' usage was :

print("#" x 78, "\n");

Which concatenates 78 times the string "#". But recently I came across this code:

while (<>) { print if m{^a}x }

Which prints every line of input starting with an 'a'. I understand the regexp matching part (m{^a}), but I really don't see what that 'x' is doing here.

Any explanation would be appreciated.

like image 513
OMG_peanuts Avatar asked Jun 30 '10 14:06

OMG_peanuts


3 Answers

It's a modifier for the regex. The x modifier tells perl to ignore whitespace and comments inside the regex.

In your example code it does not make a difference because there are no whitespace or comments in the regex.

like image 102
sepp2k Avatar answered Oct 11 '22 20:10

sepp2k


The "x" in your first case, is a repetition operator, which takes the string as the left argument and the number of times to repeat as the right argument. Perl6 can replicate lists using the "xx" repetition operator.

Your second example uses the regular expression m{^a}x. While you may use many different types of delimiters, neophytes may like to use the familiar notation, which uses a forward slash: m/^a/x

The "x" in a regex is called a modifier or a flag and is but one of many optional flags that may be used. It is used to ignore whitespace in the regex pattern, but it also allows the use of normal comments inside. Because regex patterns can get really long and confusing, using whitespace and comments are very helpful.

Your example is very short (all it says is if the first letter of the line starts with "a"), so you probably wouldn't need whitespace or comments, but you could if you wanted to.


Example:

m/^a     # first letter is an 'a'  
         # <-- you can put more regex on this line because whitespace is ignored
         # <-- and more here if you want
 /x
like image 45
vol7ron Avatar answered Oct 11 '22 22:10

vol7ron


In this use case 'x' is a regex modifier which "Extends your pattern's legibility by permitting whitespace and comments." according to the perl documentation. However it seems redundant here

like image 38
bjg Avatar answered Oct 11 '22 20:10

bjg