Perl
The function CompareStrings
takes any number of strings and returns the strings true
or false
:
true
is returned if there are one or more strings and all strings are equal.
false
is returned if there is no string or at least two different strings.
sub CompareStrings (@) {
my %hash = map { $_ => 1 } @_;
return ('false', 'true')[not scalar(keys %hash) - 1];
}
The strings are put as keys in a hash. If there is at least one string and all strings are equal, then the hash has one key exactly. Otherwise there are zero or two or more keys. After 1 is subtracted the operator not
maps the cases to the empty string and 1
that are used to select the result string (the empty string becomes 0).
sub CompareStrings (@) {
my %hash = map { $_ => 1 } @_;
return ('false', 'true')[not scalar(keys %hash) - 1];
}
Complete script with test cases:
#!/usr/bin/env perl
use strict;
$^W=1;
sub CompareStrings (@) {
# several variants to initialize the hash, whose keys are the strings:
# my %hash; @hash{@_} = (1) x @_;
# my %hash; $hash{$_} = 1 for @_;
my %hash = map { $_ => 1 } @_;
return ('false', 'true')[not scalar(keys %hash) - 1];
}
# Testing
$\ = "\n";
print CompareStrings qw[]; # false
print CompareStrings qw[foobar]; # true
print CompareStrings qw[hello hello]; # true
print CompareStrings qw[Hello World]; # false
print CompareStrings qw[abc abc abc]; # true
print CompareStrings qw[abc abc def]; # false
print CompareStrings qw[abc def ghi]; # false
print CompareStrings qw[a a a a a a a a]; # true
print CompareStrings qw]a a a a oops a a]; # false
__END__
if(string1==string2)return string2==string3;return false
– mniip Mar 18 at 17:33true & true
is actually the same astrue && true
. – ProgramFOX Mar 18 at 17:36