Reputation: 869
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";
}
}
}
}
}
Upvotes: 2
Views: 204
Reputation: 1735
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.
Upvotes: 2
Reputation: 37146
Just replacing the given
/when
s with if
/elsif
s 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.
Upvotes: 7
Reputation: 180
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
Upvotes: 3