mike1977 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I am new to perl and i am trying to open up a PCL file and search for a string and once i have found that string get the position of whats after it so i can tell how many images would be in it and have been looking at the index and pos command but they dont seem to work?

sub get {

$data_file = $file ;

open(DAT, $data_file) || die("Could not open file!");

@raw_data=<DAT>;

$search="1 of";

foreach $line (@raw_data){

if ($line =~ /$search/){


$count++ ;

}

}

print "Packs returned: $count\n";

}



Any help would be greatfully recieved ?

Replies are listed 'Best First'.
Re: Search PCL file
by MidLifeXis (Monsignor) on Nov 05, 2008 at 18:10 UTC

    What results are you getting, and what results do you expect? Perhaps also a description of what you code is doing may help you help yourself find the error....

    sub get { # Is this assignment necessary? $data_file = $file ; # 2 argument form of open(), non-lexical file handle, # and using stronger binding "||" instead of "or". # Could be better as: # open(my $dat, "<", $data_file) or die(...); open(DAT, $data_file) || die("Could not open file!"); @raw_data=<DAT>; # Careful here, will also catch "11 of", "21 of", ... $search="1 of"; foreach $line (@raw_data){ if ($line =~ /$search/){ # You are counting the number of times you match, # not the number after the match. Also, it does # not look like this is ever initialized. $count++ ; } } print "Packs returned: $count\n"; }

    If I understand your post correctly, you want instead to match the (watch for the hint here) number after your search string.

    If your intent is actually to count the number of times that you see your search string, you can do that more efficiently* using scalar and grep.

    * - for some definition of "more efficient".

    --MidLifeXis

Re: Search PCL file
by toolic (Bishop) on Nov 05, 2008 at 18:15 UTC
    Please remove the "br" tags from your original posting, then enclose your code in "code" tags, as described in Writeup Formatting Tips.

    Can you show a short segment (10 lines or fewer) of your PCL file? I'm not sure what a PCL file is or what it looks like.

    It would also be helpful if you show us how you are trying to use pos and index.

    Your "get" sub looks like it's just counting the number of lines on which a certain string occurs. Another way to code this is:

    use strict; use warnings; print "Packs returned:", get('foo.pcl'), "\n"; sub get { my $data_file = shift; my $count = 0; open my $fh, '<', $data_file or die "Could not open file: $!"; while (<$fh>) { $count++ if /1 of/; } close $fh; return $count; }