Sandra Schlichting
Sandra Schlichting

Reputation: 26026

What does this code do?

This does what I would like it to

if (grep {/$dn/} @ad_sys) {
    $is_system = 1;
}

but this always returns 1.

if (grep $_ == $dn, @ad_sys) {
    $is_system = 1;
}

What does the second piece do?

Upvotes: 3

Views: 121

Answers (3)

Dave Cross
Dave Cross

Reputation: 69314

There are two differences between the two pieces of code.

Firstly, as others have pointed out already, there is the issue of the numeric comparison operator.

But secondly, /$dn/ checks to see if $_ contains the data in $dn. $_ eq $dn checks if $_ is exactly equal to $dn.

This difference could cause a problem, for example, if your data consisted of lines read from a file that hadn't been chomped to remove the newline.

Upvotes: 3

Matteo Riva
Matteo Riva

Reputation: 25060

== is used for numeric comparison, if you need string comparison use eq.

Upvotes: 5

Ingo
Ingo

Reputation: 36339

It filters those elements from the list @ad_sys that are numerically equal to $dn. Then, if the result is not empty, the condition is true and the if-block is entered.

Upvotes: 4

Related Questions