Perl expression help...

Pls. advise what is the meaning of below expression...

if ($filename =~ /x([a-zA-Z0-9_\.]+), [0-9]+ bytes/)

--with the 1st enclosed parenthesis...
/x([a-zA-Z0-9_\.]+)

this will match/filter all the filenames with any character, number, or underscore, and /x modifiers means I can put whitespace characters (like spaces, tabs, and newlines) into the expression. ??

-- but not sure with this [0-9]+ bytes/

many thanks... :slight_smile:

if ($filename =~ /x([a-zA-Z0-9_\.]+), [0-9]+ bytes/)

I suspect it is used to extract a file name from a report as it sets $1 to "name.txt" if the value "xname.txt, 4096 bytes" is found in he variable $filename

So how does it do that, if the value contained in the $filename variable matches the following pattern then do whatever is in the block following this expression.

Pattern Breakdown
/x # an x
([a-zA-Z0-9_\.]+) # followed by any word character or a literal dot one or more times,
# the brackets indicate that we should store the matched value
# it can be accessed in the containing block as $1
#This clause could be more neatly written as ([\w\.]+)
,\s[0-9]+#followed by a comma a space and more than one digit
#The \s representation of a space is required 
#if you allow comments in a regex
\sbytes #Followed by another space and the word bytes
/x # Added by me, allow comments in the regex.

The curious thing is that you can do this with any complex regex to help the person who has to maintain your code later, but I rarely see it used :frowning:

To find out more about how Perl's regular expressions work

perldoc perlre
1 Like

There is a small slip in the explanation:

Should be

2 Likes