Skip to content

Instantly share code, notes, and snippets.

@btrott
Created November 2, 2010 18:11
Show Gist options
  • Save btrott/660038 to your computer and use it in GitHub Desktop.
Save btrott/660038 to your computer and use it in GitHub Desktop.
Perl implementations of the list2str functions at http://www.python.org/doc/essays/list2str.html.
#!/usr/bin/perl -w
use strict;
use Benchmark qw( timethese cmpthese );
use List::Util qw( reduce );
my $list = rand_chars( 256 );
cmpthese( shift || 1, {
f1 => sub { f1( $list ) },
f2 => sub { f2( $list ) },
f3 => sub { f3( $list ) },
f6 => sub { f6( $list ) },
f7 => sub { f7( $list ) },
} );
sub f1 {
my( $list ) = @_;
my $str = '';
for my $item ( @$list ) {
$str .= chr( $item );
}
return $str;
}
sub f2 {
my( $list ) = @_;
return reduce { $a . chr( $b ) } '', @$list;
}
sub f3 {
my( $list ) = @_;
my $str = '';
for my $char ( map { chr } @$list ) {
$str .= $char;
}
return $str;
}
sub f6 {
my( $list ) = @_;
return join '', map { chr } @$list;
}
sub f7 {
my( $list ) = @_;
return pack 'C*', @$list;
}
sub rand_chars {
my( $length ) = @_;
my $digits = 'abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789';
my $total = length $digits;
my @out;
for ( 1 .. $length ) {
push @out, ord substr $digits, int( rand $total ), 1;
}
return \@out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment