Thanks for the suggestions! I have now been introduced to EACH - something I have never really used.
It also made me read the JOIN doc more carefully - here is an inefficient, but fun OOlternative :).
use strict;
my %hash = (
apple => 'pie',
banana => 'custard',
cherry => 'ripe',
);
# use map to alternate $delim between = and ,
my $delim = '';
my $str = join $delim, map { $delim = ($delim eq ',' ? '=' : ','); $_
+} %hash;
print "result: [$str]\n";
# use class stringification overload to alternate
my $str2 = join( flipper->new(), %hash );
print "result: [$str2]\n";
#----------------------------------
package flipper;
use overload '""' => \&toString;
sub new {
my $class = shift;
my $self = { counter => 0 };
bless $self, $class;
}
sub toString {
my $self = shift;
return ( $self->{counter}++ % 2 ? '=' : ',' );
}
Does anyone have a more elegant use of the fact that JOIN stringifies the EXPR for each element? perhaps an anon-sub closure??
|