What does =~/^0$/ mean in Perl?

I'm new to Perl and I have been learning about the Perl basics for past two days. I'm converting a Perl script to Java program gradually. In the Perl script, I came across this code.

if( $arr[$i]=~/^0$/ ){
...
...
}

I know that $arr[$i] means getting the ith element from the array arr.

But what does =~/^0$/ mean?

To what are they comparing the array's element?

I searched for this, but I couldn't find it.

Someone please explain me.

FYI, the arr contains floating values.

Upvotes: 2

Views: 2875

Answers (3)

Dave Sherohman
Dave Sherohman

Reputation: 46187

if ($arr[$i]) =~ /^0$/) is roughly equivalent to if ($arr[$i] eq "0"), but not exactly the same, as it will match both the strings "0" and "0\n". If $arr[$1] was read from a file or stdin and it has not been chomped, this can be a very significant distinction.

if ($arr[$i] == 0), on the other hand, will match any string beginning with a non-numeric character or a string of zeroes/whitespace which is not followed by a numeric character, although it will generate a warning if the string contains non-whitespace, non-digit characters or contains only whitespace (and warnings are enabled, of course).

Upvotes: 10

mpapec
mpapec

Reputation: 50637

^ and $ are regex anchors which says $arr[$i] should begin with 0 and there is end of string immediately after it.

It can be written as

if ($arr[$i] eq "0" or $arr[$i] eq "0\n")

Upvotes: 9

chrsblck
chrsblck

Reputation: 4088

=~ is a binding operator.

"Binary "=~" binds a scalar expression to a pattern match"

/^0$/ on the right hand side is the regex

^        Match the beginning of the line
$        Match the end of the line (or before newline at the end)

And the zero has no special meaning.

Upvotes: 9

Related Questions