Thursday, 5 November 2009

unless and until

These two are always confusing for me to remember, yet i found a way of remembering the difference between them.

Example :

$line = undef;
unless($line) { print "will enter here" }
unless means if $line is undefined, then enter the loop.Similary we can use this to build a the hash key value pairs as follows.

Below code says for each word, unless the hash key is defined enter inside.This is used for taking repeated words only once of a line.
foreach (@words)
{
unless( exists $hash{$_} )
{
push @uniq,$_ ; #gets word only once
}
}

Notes:

%hash has keys as the words and @uniq array will contains uniq words only.

"exists" is hash function to see if a value exists for a key.

Difference between until and unless :
until says : if condition is true or exists, then don't enter .
unless says : if condition is not true or not exists, then enter.

No comments:

Post a Comment

Tweets by @sriramperumalla