William Li wrote:
>
> Silly question, is there an equal but opposite function to chop in Perl?
> I'd like to remove the first and last character of a string and am looking
> for a simple way to do it.  So far I have:
>
> # "1234567" -> "23456"
> chop($string); # "123456"
> $string = reverse($string); # "654321"
> chop($string); # "65432"
> $string = reverse($string); # "23456"

Hi.

To resolve the problem, I ran the benchmark below and got these results:

Benchmark: timing 10000000 iterations of Control, One Substitute, One Substring, Two 
Substitutes, Two Substrings...
   Control: 25 wallclock secs (25.43 usr +  0.00 sys = 25.43 CPU) @ 393236.34/s 
(n=10000000)
One Substitute: 112 wallclock secs (111.50 usr +  0.00 sys = 111.50 CPU) @ 89686.10/s 
(n=10000000)
One Substring: 54 wallclock secs (53.28 usr +  0.00 sys = 53.28 CPU) @ 187687.69/s 
(n=10000000)
Two Substitutes: 62 wallclock secs (62.12 usr +  0.00 sys = 62.12 CPU) @ 160978.75/s 
(n=10000000)
Two Substrings: 57 wallclock secs (57.57 usr +  0.00 sys = 57.57 CPU) @ 173701.58/s 
(n=10000000)

Subtracting the control time from the four options gives

One Substitute: 87 secs
One Substring: 29 secs
Two Substitutes: 37 secs
Two Substrings: 32 secs

So the fastest by a nose is Tore's

  $string = substr( $string, 1, (length($string) - 2) )

although the three fastest are remarkably similar. As predicted James'
single substitution

  $string =~ s/^.(.*).$/$1/;

was by far the slowest, but by just three times rather than the 20+ times
that Rob H had predicted.

Cheers,

Rob



  use strict;
  use warnings;

  use Benchmark;

  timethese(10E6, {

      'Control' => sub {
        my $str = join '', 'A' .. 'Z';
      },

      'Two Substitutes' => sub {
        my $str = join '', 'A' .. 'Z';
        for ($str) {
          s/^.//s;
          s/.$//s;
        }
      },

      'One Substitute' => sub {
        my $str = join '', 'A' .. 'Z';
        for ($str) {
          s/^.(.*).$/$1/s;
        }
      },

      'Two Substrings' => sub {
        my $str = join '', 'A' .. 'Z';
        for ($str) {
          substr($_, 0, 1, '');
          substr($_, -1, 1, '');
        }
      },

      'One Substring' => sub {
        my $str = join '', 'A' .. 'Z';
        for ($str) {
          $_ = substr ($_, 1, (length($str) - 2) );
        }
      },
  });



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to