Arty Arty - 3 months ago 11
Perl Question

What does "$file =~ /^\./" mean in perl?

I'm just getting started in Perl, and I've been given a script that I don't fully understand. Specifically, I don't understand this condition line:

if ( -d "$dirPath\\$file" and not $file =~ /^\./ )


The first part of the condition is whether the file exists in the directory, but I don't understand the "not $file =~ /^./ ", what does it mean ?
I did some research through the internet but wasn't able to find anything.

Answer

The not $file =~ /^\./ part of that statement tests the string in the scalar $file against the regex ^\.

The regex checks for ^ begining of string, followed by .

Dots (periods) have to be escaped with a backquote \ because in regex dots have a special meaning (it means any single character).

So it will check if the string inside $file starts with a dot. This operation will return 1 if it matches or 0 if it doesn't and the not negates it. The upshot can been read as "if the file does not start with a dot".

You can also use the !~ operator (does not match regex operator) to achieve the same result:

if ( -d "$dirPath\\$file" and $file !~ /^\./ )

To link some of ThisSuitIsNotBlack comments here in an answer, the matches operator =~ is documented inside perl documentation page perlop, which can be viewed with perldoc perlop and can be found online at the Perl website. The relevant section is Binding Operators. Perl Regex has a couple of perl documentation pages perlretut (perldoc perlretut) and perlre (perldoc perlre).