Gossamer Forum
Home : General : Perl Programming :

problem on linear search (perl programming)

Quote Reply
problem on linear search (perl programming)
Hi all,

I've found some codes from 'Mastering Algorithms with Perl' O'Reilly.

Code:
sub linear_string
{
my ($array, $target) = @_;
for (my $i = @$array; $i--;)
{
print("$array->[$i]\n");
return $i if $array->[$i] eq $target;
}
return undef;
}

$path= 'd:\\atlog.txt';
open(LOGFILE, "< $path")
or die "Couldn't open $path for reading: $!\n";

$target = 'test';
while (<LOGFILE>)
{
@string= split(/\s+/, $_);
$index = linear_string( \@string, $target);
print("@string($index)");
print("$index\n");
}

It doesn't work! I mean it cannot search my 'target' string. Also it cannot print $index...

My 'atlog.txt' does contain the 'target' string.

Any idea?

Thanks
Cary

Last edited by:

caryhung: Apr 28, 2002, 5:29 AM
Quote Reply
Re: [caryhung] problem on linear search (perl programming) In reply to
You forgot to close the FH too :)

Hmm try something like:

Code:
my $path = 'd:\\atlog.txt';
my $target = 'test';
my $found;

open(LOGFILE, "<$path") or die "Couldn't open $path for reading: $!\n";
while (<LOGFILE>) {
chomp;
if (grep { /^\Q$target\E$/i } (split /\s+/)) {
$found = 1;
last;
}
next;
}
close (LOGFILE);

print $found ? 'OK' : 'NOT OK';

Last edited by:

Paul: Apr 28, 2002, 6:12 AM
Quote Reply
Re: [Paul] problem on linear search (perl programming) In reply to
Hi Paul,

Thank you for your reply.

And I would like to get '$index' after searching. Do you see what I mean?

Regard
Cary
Quote Reply
Re: [caryhung] problem on linear search (perl programming) In reply to
Change:

Code:
if (grep { /^\Q$target\E$/i } (split /\s+/)) {
$found = 1;
last;
}
next;

to...

Code:
my $i = 0;
for (split /\s+/) {
$i++;
if (/^\Q$target\E/i) {
$found = $i;
last;
}
}

Then the index is stored in $found