in reply to Check for Spaces in a String
You may be better off doing the initial check without using the regex engine; only using it with split where necessary.
As you can see from ++aaron_baugher's analysis, your results will depend on your real data. Furthermore, if your volume of data is small, your choice of solution may make little difference (in terms of runtime).
Here's a solution using substr, rindex and length for the initial check. As a proof-of-concept to show that these functions work on characters (as opposed to bytes), I've included single-byte and multi-byte characters in the data.
#!/usr/bin/env perl -l use strict; use warnings; use utf8; use open OUT => ':utf8', ':std'; my @strings = ( 'A B C', 'D E', 'F ', 'G', 'H ', 'I ', "\N{MERCURY} \N{FEMALE SIGN} \N{EARTH}", "\N{MALE SIGN} \N{JUPITER +}", "\N{SATURN} ", "\N{URANUS}", "\N{NEPTUNE} ", "\N{PLUTO} ", ); for (@strings) { next if substr($_, -1, 1) eq ' ' or rindex($_, ' ', length() - 2) +== -1; print; }
Output:
A B C D E ☿ ♀ ♁ ♂ ♃
[The Unicode range of characters labelled "Astrological symbols" is 0x263d to 0x2647. There is no charname for "VENUS" or "MARS"; the charnames "FEMALE SIGN" and "MALE SIGN" are defined for these symbols, respectively.]
Here's a benchmark test. This uses my sample data. If you choose this route, you should benchmark with representative samples of your data.
#!/usr/bin/env perl -l use strict; use warnings; use Benchmark qw{cmpthese}; my @strings = ( 'A B C', 'D E', 'F ', 'G', 'H ', 'I ', "\N{MERCURY} \N{FEMALE SIGN} \N{EARTH}", "\N{MALE SIGN} \N{JUPITER +}", "\N{SATURN} ", "\N{URANUS}", "\N{NEPTUNE} ", "\N{PLUTO} ", ); my $re = qr{\s+\b}; cmpthese -1 => { no_re_check_and_split => \&no_re_check_and_split, re_check_and_split => \&re_check_and_split, split_and_re_check => \&split_and_re_check, }; sub no_re_check_and_split { for (@strings) { next if substr($_, -1, 1) eq ' ' or rindex($_, ' ', length() - + 2) == -1; my @parts = split /$re/; } } sub re_check_and_split { for (@strings) { next unless /$re/; my @parts = split /$re/; } } sub split_and_re_check { for (@strings) { my @parts = split /$re/; next if @parts > 1; } }
Here's three sample runs:
Rate split_and_re_check re_check_and_split no +_re_check_and_split split_and_re_check 50243/s -- -18% + -29% re_check_and_split 61265/s 22% -- + -13% no_re_check_and_split 70274/s 40% 15% + -- Rate split_and_re_check re_check_and_split no +_re_check_and_split split_and_re_check 53593/s -- -19% + -27% re_check_and_split 66370/s 24% -- + -10% no_re_check_and_split 73770/s 38% 11% + -- Rate split_and_re_check re_check_and_split no +_re_check_and_split split_and_re_check 53096/s -- -20% + -27% re_check_and_split 66369/s 25% -- + -8% no_re_check_and_split 72404/s 36% 9% + -- ken@ganymede: ~/tmp
With my sample data, doing the initial check without a regex appears faster. Again, I'll stress, you'll need to check with your data.
-- Ken
|
|---|