zlenyk
zlenyk

Reputation: 1000

'if' after assignment

What is the following line supposed to do in Perl?

$result{$key} .= ";" if (exists($result{$key}));

It looks like it adds ";" at the end of the key when it already exists. Is it true?

Is it different than putting the "if" statement before assigning?

Upvotes: 2

Views: 719

Answers (5)

serenesat
serenesat

Reputation: 4709

$result{$key} .= ";" if (exists($result{$key}));

can be written as:

if (exists($result{$key}))
{
    $result{$key} .= ';';
}

There isn't any difference.

Upvotes: 1

Sobrique
Sobrique

Reputation: 53478

Perl allows you to do conditional statements either before or after.

This is to allow you to do things like:

return unless $configured;
exit if $bored;

print "Debug statement\n" if $debug;

while ( <STDIN> ) {
    print if m/text/;
}

So yes, you're right - that's a conditional append in that if the key exists, it'll stick a semicolon on the end of the value. (As noted in comments - it does not change the key.)

It isn't any different to:

if ( exists ( $result{$key} ) ) {
    $result{$key} .= ';';
}

Generally, it's a style and maintainability question as to which you use. I would generally suggest avoiding it, because it generally makes things less clear. (But not always - see above for a couple of examples.)

Upvotes: 6

kvivek
kvivek

Reputation: 3461

1) Could someone tell me what is this line supposed to do in perl:

$result{$key} .= ";" if (exists($result{$key}));

Answer: The above expression can be read as

if ( exists ( $result{$key} ) ) {   
    $result{$key} .= ';';
}

Explanation: if condition checks for existence of value obtained from the hash result(%result) with the key as $key, If the value exists then append the semicolon to the end of the value.

2) It looks like it adds ";" at the end of key when it already exists, is it true?

NO, Semicolon will be added to the end of the value and not at the end of the key, when it(value) exists, as value for a key is obtained from hash via $hashName{$keyName}

Example:

C:\Users\kvivek>perl

my %fruit_color = (
    apple  => "red",
    banana => "yellow",
);

print $fruit_color{"apple"};
print "\n";
__END__
red

C:\Users\kvivek>

3)Is it different than putting "if" statement before assigning?

No, It is not different, but an another way writing.

Upvotes: 2

ikegami
ikegami

Reputation: 385657

It's exactly as you said. It means:

If the hash %result has an element with key $key, append ; to the element's value.

because

$result{$key} .= ";" if (exists($result{$key}));

is just another way of writing

if ((exists($result{$key}))) {
    $result{$key} .= ";";
}

Upvotes: 1

rubikonx9
rubikonx9

Reputation: 1413

$result{$key} .= ";" if (exists($result{$key}));

and

if (exists($result{$key})) {
    $result{$key} .= ";";
}

do exactly the same thing. There are times where you may prefer one over another for better readability.

Upvotes: 0

Related Questions