user99999991
user99999991

Reputation: 1421

What does =~ m/\#F/ mean in Perl?

open DMLOG, "<dmlog.txt" or &error("Can't open log file: $!");
chomp(@entirelog=<DMLOG>);
 close DMLOG;
 for $line (@entirelog) 
{

if ($line =~ m/\#F/)
    {
    $titlecolumn = $line;
    last;
     }
 }

I found that =~ is a regular expression I think, but I don't quite understand what its doing here.

Upvotes: 1

Views: 1703

Answers (4)

David W.
David W.

Reputation: 107080

Do you understand what regular expressions are? Or, is the =~ throwing you off?

In most programming languages, you would see something like this:

 if ( regexp(line, "/#F/") ) {
   ...
}

However, in Perl, regular expressions are inspired by Awk's syntax. Thus:

if ( $line =~ /#F/ ) {
   ...
}

The =~ means the regular expression will act upon the variable name on the left. If the pattern #F is found in $line, the if statement is true.

You might want to look at the Regular Expression Tutorial if you're not familiar with them. Regular expressions are extremely powerful and very commonly used in Perl. In fact, they tend to be very used in Perl and is one of the reasons developers in other languages will claim that Perl is a Write Only language.

Upvotes: 3

Karsten S.
Karsten S.

Reputation: 2391

Yes, =~ is the binding operator binding an expression to the pattern match m//.

The if statement checks, if a line matches the given regular expression. In this case, it checks, if there is a hash-sign followed by a capital F.

The backslash has just been added (maybe) to avoid treating # as a comment sign (which isn't needed).

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213351

It is called Binding Operator. It is used to match pattern on RHS with the variable on LHS. Similarly you have got !~ which negates the matching.

For your particular case:

$line =~ m/\#F/

This test whether the $line matches the pattern - /#F/.

Upvotes: 3

amon
amon

Reputation: 57640

It assigns the first line to $titlecolumn that contains an # followed by an F.

The =~ is the bind operator and applies a regex to a string. That regex would usually be written as /#F/. The m prefix can be used to emphasize that the following literal is a prefix (important when other delimiters are used).

Upvotes: 6

Related Questions