On Wed, Jun 17, 2015 at 07:01:06AM +1200, Kent Fredric wrote:
> On 17 June 2015 at 04:46, Vincent Lequertier <[email protected]> wrote:
> >
> > #!/usr/bin/perl
> > use strict;
> > use warnings;
> > open my $fh, '<', 'text';
> > my @words = split ' ', <$fh>;
> > my @matchs;
> > while (my ($index, $elem) = each @words) {
> > if ($elem eq 'bspwrt') {
> > push @matchs, $index++;
> > }
> > }
> > $, = ' ';
> > print @matchs;
>
>
> Obviously that strategy may be limited and slow if you need to execute
> the lookup > 3 times for several queries.
>
> That can be avoided by using a hash representation of the data, etc:
>
> my @words = split ' ', <$fh>;
> my %match_index;
> while (my ($index, $elem) = each @words) {
> $match_index{ $elem } = [] unless exists $match_index{ $elem };
> push @{ $match_index{$elem} }, $index;
> }
> $, = '';
> print @{ $match_index{'bspwrt'} };
> print @{ $match_index{'tnbcch'} };
>
> etc.
Or, if you can't be bothered writing all that code:
$ perl -E 'push @{$pos{$_}}, $i++ for map split, <STDIN>; say "$_: @{$pos{$_}}"
for @ARGV' bccd sdcch < data
bccd: 8 98 188 278 368 458 548 638 728 818 908 998 1088 1178 1268 1358
sdcch: 81 171 261 351 441 531 621 711 801 891 981 1071 1161 1251 1341 1431
$
Thinking about it, there is (at least) one bug in there. But with the
data provided it may not be important.
--
Paul Johnson - [email protected]
http://www.pjcj.net
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/