swapnil
swapnil

Reputation: 77

What is does the regular expression /^\s*$/ do?

What does this expression in Perl programming do?

$variable =~ /^\s*$/;

Upvotes: 3

Views: 8438

Answers (4)

Berzemus
Berzemus

Reputation: 3658

=~ is a match operator.

The statement returns true if $variable only consists of spaces, or is simply empty.

So it just checks if the string is empty or not.

Upvotes: 1

Alex Brown
Alex Brown

Reputation:

Nothing, since you are not assigning the result of this operation to any variable, and since it has no side effects that you are likely to test for.

However, if you said

if ($variable =~ /^\s*$/)
{
  print "something";
}

You would be answering the question:

Does the value in variable consist of an empty line or a line consisting of nothing but non printing whitespace characters such as spaces and tabs?

Upvotes: 1

Sinan Ünür
Sinan Ünür

Reputation: 118158

 if ( $variable =~ /^\s*$/ )

is the same as

 unless ( $variable =~ /\S/ )

or

 if ( $variable !~ /\S/ )

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272347

That's looking for a line start (^), followed by zero or more whitespace (\s*) characters, followed by a line end ($).

It's essentially looking for blank/empty lines.

I'd expect the expression to be used in something like:

if ($v =~ /^\s*$/) {
   # found a blank line
}

in order to perform the check and a following action.

Upvotes: 23

Related Questions