Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences beteween switch- and if-statements

Do these two statements behave equally or could they yield different results?

if ( ... ) {...}
elsif( ... ) {... }
elsif( ... ) { ... }
else { ... }

.

given ( ... ) {
    when ( ... ) { ... }
    when ( ... ) { ... }
    default { ... }
}

I've found the problem - with a modified ninth "when" it works now.

...
no warnings qw(numeric);
my $c = &getch();

given ( $c ) {
when ( $c == $KEY_LEFT and 1 > 0 ) { say 1; say $c }
when ( $c == $KEY_RIGHT ) { say 2; say $c } 
when ( $c eq "\cH" or $c eq "\c?" ) { say 3; say $c } 
when ( $c eq "\cC" ) { say 4; say $c } 
when ( $c eq "\cX" or $c eq "\cD" ) { say 5; say $c } 
when ( $c eq "\cA" ) { say 6; say $c } 
when ( $c eq "\cE" ) { say 7; say $c } 
when ( $c eq "\cL" ) { say 8; say $c } 
when ( not( not $SpecialKey{$c} ) ) { say 9; say $c } 
when ( ord( $c ) >= 32 ) { say 10; say $c } 
default { say 11; say $c }
}

if ( $c == $KEY_LEFT and 1 > 0 ) { say 1; say $c }
elsif ( $c == $KEY_RIGHT ) { say 2; say $c } 
elsif ( $c eq "\cH" or $c eq "\c?" ) { say 3; say $c } 
elsif ( $c eq "\cC" ) { say 4; say $c } 
elsif ( $c eq "\cX" or $c eq "\cD" ) { say 5; say $c } 
elsif ( $c eq "\cA" ) { say 6; say $c } 
elsif ( $c eq "\cE" ) { say 7; say $c } 
elsif ( $c eq "\cL" ) { say 8; say $c } 
elsif ( $SpecialKey{$c} ) { say 9; say $c } 
elsif ( ord( $c ) >= 32 ) { say 10; say $c } 
else { say 11; say $c }

close TTYIN;
like image 638
sid_com Avatar asked Feb 26 '23 17:02

sid_com


1 Answers

Your supposedly "fixed" version now does different things in the two versions of the code. Checking if a key exists in a hash is completely different to checking whether the associated value is true.

There are three different truth values you can get from a hash - whether the key exists in the hash, whether the associated value is defined and whether the associated value is true or false. This code should demonstrate the difference between the three:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
  key1 => undef,
  key2 => 0,
  key3 => 1,
);

foreach (qw(key1 key2 key3 key4)) {
  check_key($_);
}

sub check_key {
  my $k = shift;

  print "Key $k ";
  if (exists $hash{$k}) {
    print 'exists. ';
  } else {
    print "doesn't exist. ";
  }

  print 'Value ';

  if (defined $hash{$k}) {
    print 'is defined ';
  } else {
    print 'is not defined ';
  }

  print 'and is ';

  if ($hash{$k}) {
    print "true\n";
  } else {
    print "false\n";
  }
}
like image 70
Dave Cross Avatar answered Mar 03 '23 02:03

Dave Cross