perlperl5.8

how to port code perl switch-like statement for use with 5.8


I have this particular code that is using perl 5.10 (for switch-like operation), but need to get it to work on 5.8. What's another way to write this for 5.8? A preferred way/technique?

for my $detail ($Details1, $Details2) {
    for (keys %$detail) {
        when ('file') {
            print " File: $detail->{file}{path}\n";
            print "Bytes: $detail->{file}{size}\n";
        }

        when ('directory') {
            given (ref $result->{directory}) {
                when ('ARRAY') {
                    for my $entry (@{$detail->{directory}}) {
                        print "Directory: $entry->{path}\n";
                    }
                }
                when ('HASH') {
                    print "Directory: $detail->{directory}{path}\n";
                }
            }
        }
    }
}

Solution

  • Just replacing the given/whens with if/elsifs is simple enough.

    for my $detail ( $Details1, $Details2 ) {
    
        for ( keys %$detail ) {
    
            if ( $_ eq 'file' ) {
    
                print " File: $detail->{file}{path}\n";
                print "Bytes: $detail->{file}{size}\n";
            }
    
            elsif ( $_ eq 'directory' ) {
    
                if ( ref $result->{directory} eq 'ARRAY' ) {
    
                    for my $entry ( @{$detail->{directory}} ) {
                        print "Directory: $entry->{path}\n";
                    }
                }
    
                if ( ref $result->{directory} eq 'HASH' ) {
                    print "Directory: $detail->{directory}{path}\n";
                }
            }
        }
    }
    

    But I'm tempted to rewrite this as anonymous subs with a dispatch table.