Sagar Samtani
Sagar Samtani

Reputation: 203

How to use the && operator in Perl

I am new to Perl and am trying to use the following code to execute a print statement if it satisfies two conditions.

if ($ARGV[0] eq "test") && ($ARGV[1] eq "test1"){
print"test and test1 Selected\n"
}

How can I adjust the code such that it does not throw any errors?

Upvotes: 2

Views: 13494

Answers (2)

hata
hata

Reputation: 12478

You may put these conditions inside of if-clause.

if (($ARGV[0] eq "test") && ($ARGV[1] eq "test1")) {
    print"test and test1 Selected\n"
}

(So my making unnecessary addition with rough description about logical conjunction operators had some confusing problems and caused criticism that I removed it totally.)

For your question here, I think that simply nesting use of bracket is the point.

Upvotes: 4

ikegami
ikegami

Reputation: 385655

The syntax for the if statement is:

if (CONDITION) BLOCK

so if your condition is

($ARGV[0] eq "test") && ($ARGV[1] eq "test1")

then you'd use

if (($ARGV[0] eq "test") && ($ARGV[1] eq "test1")) { ... }

That said, those parens are not needed because && is meant to be used exactly like that.

if ($ARGV[0] eq "test" && $ARGV[1] eq "test1") { ... }

I don't know why the other two suggested disguising && with the lower-precedence and. There's a reason symbols are used to for separators (e.g. ,, ;, { ... }, etc) and it's because it makes it easier to find boundaries in the code at a glance, improving readability.

As such, the most commonly-used convention by far is to use or and and for flow control (or die, or next, or return, etc.), and use || and && in expressions (as you did).

Upvotes: 14

Related Questions