From: mud_saisem on
Hi There,

Does anybody know how to read through a file searching for a word and
printing the file position of that word ?

Thanks.
From: Tad McClellan on
mud_saisem <mud_saisem(a)hotmail.com> wrote:

> Does anybody know how to read through a file searching for a word and
^^^^^^^^^
> printing the file position of that word ?


-----------------------
#!/usr/bin/perl
use warnings;
use strict;

my $pos;
while (<DATA>) {
if ( /(.*)searching/ ) {
print $pos + length $1, "\n";
exit;
}
$pos += length;
}

__DATA__
Hi There,

Does anybody know how to read through a file searching for a word and
printing the file position of that word ?

Thanks.
-----------------------


--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.liamg\100cm.j.dat/"
From: Peter Makholm on
mud_saisem <mud_saisem(a)hotmail.com> writes:

> Does anybody know how to read through a file searching for a word and
> printing the file position of that word ?

If your file contains plain ascii, iso-8859, or another 8bit charset
it should be easy. The tell() function gives you the current location
in the file, pos() gives you the location of regexp match, and
index() directly gives you the location.

So this should work (untested though)

my $offset = 0;
while (<$fh>) {
if (/word/) {
say "Found 'word' at location ", $offset + pos();
}
$offset = tell $fh;
}

If you file contains a variable width uniode encoding (like utf-8) it
gets a lot harder.


//Makholm
From: mud_saisem on
On Feb 18, 4:22 pm, Peter Makholm <pe...(a)makholm.net> wrote:
> mud_saisem <mud_sai...(a)hotmail.com> writes:
> > Does anybody know how to read through a file searching for a word and
> > printing the file position of that word ?
>
> If your file contains plain ascii, iso-8859, or another 8bit charset
> it should be easy. The tell() function gives you the current location
> in the file, pos() gives you the location of regexp match, and
> index() directly gives you the location.
>
> So this should work (untested though)
>
>   my $offset = 0;
>   while (<$fh>) {
>       if (/word/) {
>           say "Found 'word' at location ", $offset + pos();
>       }
>       $offset = tell $fh;
>   }
>
> If you file contains a variable width uniode encoding (like utf-8) it
> gets a lot harder.
>
> //Makholm

Very Nice, Thank for the help !

From: J�rgen Exner on
mud_saisem <mud_saisem(a)hotmail.com> wrote:
>Does anybody know how to read through a file searching for a word and
>printing the file position of that word ?

Please define 'position': are you talking about characters or bytes?

Just slurp the whole file into a string and then use index() to get the
position of the desired word in that string.
This is very straight-forward and unless you are dealing with
exceptionally large files (GB size) or unusual distribution of your
'word' (almost always very early in the file) probably also faster than
any looping line by line or chunk by chunk.

jue