Question

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";
                }
            }
        }
    }
}
Was it helpful?

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.

OTHER TIPS

I think simple if-elsif would be sufficient to replace the switch-like code there.

The CPAN Switch is a source filter thus I guess it will generate similar code to if-elsif. And it has some limitation when you use it in eval: "Due to the way source filters work in Perl, you can't use Switch inside an string eval." http://perldoc.perl.org/5.8.9/Switch.html

My personal preference is to use for, a regex, and a do block:

for my $detail ($Details1, $Details2) {
    for (keys %$detail) {

        /^file$/ && do {
            print " File: $detail->{file}{path}\n";
            print "Bytes: $detail->{file}{size}\n";
        };

        /^directory$/ && do {

            for (ref $result->{directory}) {

                /^ARRAY$/ && do {
                    for my $entry (@{$detail->{directory}}) {
                        print "Directory: $entry->{path}\n";
                    }
                };

                /^HASH$/ && do {
                    print "Directory: $detail->{directory}{path}\n";
                };
            }
        };
    }
}

Don't forget the ; after each do block.

EDIT: And don't forget to use next or last if you don't want to fall through to the next case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top