ado
ado

Reputation: 1471

Difference between unless () return ... ,and return ... unless()

In Perl, is there any meaningful difference between:

return $result unless ($exist_condition);

and

unless ($exist_condition) return $result;

Upvotes: 2

Views: 3276

Answers (2)

ikegami
ikegami

Reputation: 386361

The second is a syntax error. I presume you meant

# unless statement modifier
return $result unless $exist_condition;

and

# unless statement
unless ($exist_condition) { return $result; }

They're virtually the same. One difference is that the unless statement creates a scope (two actually), while the unless statement modifier does not.

>perl -E"my $x = 'abc'; unless (my $x = 'xyz') { return; } say $x;"
abc

>perl -E"my $x = 'abc'; return unless my $x = 'xyz'; say $x;"
xyz

In practice, that will probably never come up, so the difference is merely a question of style.

Upvotes: 9

user149341
user149341

Reputation:

As currently written, the second one is a syntax error.

If changed to:

unless ($exist_condition) { return $result; }

then there is no difference whatsoever. Use whichever one makes the most sense in context.

Upvotes: 1

Related Questions