develooper Front page | perl.beginners | Postings from October 2009

Re: split n characters into n chunks

Thread Previous | Thread Next
From:
John W. Krahn
Date:
October 25, 2009 14:10
Subject:
Re: split n characters into n chunks
Message ID:
4AE4BEC4.7030003@shaw.ca
Shawn H Corey wrote:
> John W. Krahn wrote:
>> $ perl -le'
>> my $word = "thequickbrown";
>> my $subsets = 3;
>> print for $word =~ /(?=(.{$subsets}))/g;
> 
> Getting up there but substr is still the fastest.
> 
> #!/usr/bin/env perl
> 
> use strict;
> use warnings;
> 
> use Data::Dumper;
> 
> # Make Data::Dumper pretty
> $Data::Dumper::Sortkeys = 1;
> $Data::Dumper::Indent   = 1;
> 
> # Set maximum depth for Data::Dumper, zero means unlimited
> $Data::Dumper::Maxdepth = 0;
> 
> my $Testing = $ARGV[0] || 0;
> use Benchmark qw(:all);
> 
> my $word = "thequickbrown";
> my $size = 3;
> 
> if( $Testing ){
>   via_arrays();
>   via_substr();
>   via_unpack();
>   via_match();
>   via_match2();
> }else{
>   cmpthese( 50_000, {
>     'via arrays' => \&via_arrays,
>     'via substr' => \&via_substr,
>     'via unpack' => \&via_unpack,
>     'via match'  => \&via_match,
>     'via match2' => \&via_match2,
>   });
> }
> 
> 
> sub via_arrays {
>   my @array = split //, $word;
>   my $max = @array - $size;
>   my @list = ();
>   for my $i ( 0 .. $max ){
>     push @list, join '', @array[ $i .. $i+$size-1 ];
>   }
>   # print Dumper \@list;  #for testing only
> }
> 
> sub via_substr {
>   my $max = length( $word ) - $size;
>   my @list = ();
>   for my $i ( 0 .. $max ){
>     push @list, substr( $word, $i, $size );
>   }
>   # print Dumper \@list;  #for testing only
> }
> 
> sub via_unpack {
>   my $max = length( $word ) - $size;
>   my @list = ();
>   for my $i ( 0 .. $max ){
>     push @list, (unpack( "A${i}A$size", $word ))[1];
>   }
>   # print Dumper \@list;  #for testing only
> }
> 
> sub via_match {
>   my @list = ();
>   push @list, substr( $word, $-[0], 3 )
>     while $word =~ /.(?=..)/g;
>   # print Dumper \@list;  #for testing only
> }
> 
> sub via_match2 {
>   my @list = ();
>   push @list, $_ for $word =~ /(?=(.{$size}))/g;

Why the for loop?

   my @list = $word =~ /(?=(.{$size}))/g;


>   # print Dumper \@list;  #for testing only
> }



John
-- 
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About