Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is the 3rd char a 8? 1

Status
Not open for further replies.

travs69

MIS
Joined
Dec 21, 2006
Messages
1,431
Location
US
I have a data set like
1284578898
1234587899
2189589899
3456788989
1285989899

and I want to check if the third char is an 8
normally I would just

@tmp = split //, $_;
if ($tmp[2] == 8) {
Blah;
}
else {
More blah;
}

but I know there is a better way!
 
An easier way is probably going to be using substr. Here's an example that might help:
Code:
while (<DATA>) {
    chomp;
    print "$_ - Third character is ";
    print "NOT " unless substr($_,2,1) == 8;
    print "an 8.\n";
}

__DATA__
1284578898
1234587899
2189589899
3456788989
1285989899
 
Code:
while( <DATA> ) {
  print if /^..8/;
}

__DATA__
1284578898
1234587899
2189589899
3456788989
1285989899
 
Thank you both.. I had thought of using substr but it didn't seem much more efficient. I think I'm going to use the reg expression.

 
If it's efficiency you're looking for , a regexp is going to be slower. A quick benchmark with 3 different approaches backs that up:
Code:
           Rate regexp substr  index
regexp 218818/s     --    -9%   -25%
substr 239234/s     9%     --   -18%
index  292398/s    34%    22%     --

Code:
#!/usr/bin/perl -w
use strict;

use Benchmark qw(:all);

my @data = (1284578898, 1234587899, 2189589899, 3456788989, 1285989899 );

cmpthese(1000000,
{substr => \&substring,
regexp => \&regexp,
index => \&ind });

sub substring {
   return grep substr($_,2,1) eq '8', @data;
}

sub regexp {
   return grep /^..8/, @data;
}

sub ind {
   return grep index( $_, '8' ) == 2, @data;
}

One thing to note is in the comparisons. Both the substr and split functions return strings, so it's going to be more efficient to use the "eq" equality operator than "==", since the latter requires your string to be converted back into a numeric value before the comparison takes place.
 
ishnid,

Code:
  return grep index( $_, '8'[b], 2[/b]) == 2, 
@data;

Otherwise it will fail if either of the first two chars is also an '8'.

But yes, there's no doubt index() would be faster than a regex. I just went for simplicity.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top