On Jul 9, saliminl said:

>Hi.  This is my first post.  I'm trying to write a script that retrieves
>data from a text file.  The text files have several hundred instances of
>the string "EAMBER (non-constraint) = #" where the # is a number that
>can be negative and the last spacing after the equals sign is variable.  
>My problem is in the loop; my expression matches ok, but it skips every
>other instance of the expression (leaving me with half my data).  I
>added the counting variable as a debug to see what was going on, and in
>files with 600 instances of the string, it ends up at 300.  Thanks a
>lot.

That's because you're doing:

  while (<FH>) {
    $line = <FH>;
    # ...
  }

The <FH> in the while condition ALREADY stores a line into $_, so you can
use that variable.

Also, your regex leaves a bit to be desired, and you might want to use
push() to add to your array, rather than explicitly indexing it.

  #!/usr/bin/perl -w

  use strict;

  print "Input file name: \n";
  chomp (my $input = <STDIN>);

  open INPUT, "< $input" or die "can't read $input: $!";
  open OUTPUT, "> sum.EAMBER" or die "can't write to sum.EAMBER: $!";

  while (<INPUT>) {
    if (/EAMBER\s\(non-constraint\)\s=\s+(-?\d*\.?\d*)/) {
      push @EAMBER, $1;
      print OUTPUT @EAMBER - 1, " $1\n";
    }
  }

  close OUTPUT;
  close INPUT;

In fact, you don't even need an array, unless you're doing something with
the values later.  Just have a counter of some sort.

Note that my regex could match NOTHING in $1.  To fix this, you can do:

    if (/EAMBER\s\(non-constraint\)\s=\s+(-?(?=\.?\d)\d*\.?\d*)/) {

The addition of (?=\.?\d) means "look ahead to make sure we'll match an
optional . followed by a digit".  That ensures that the \d*\.?\d* WILL
actually match something (since \d*\.?\d* can match 0 characters).

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
I am Marillion, the wielder of Ringril, known as Hesinaur, the Winter-Sun.
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734
**      Manning Publications, Co, is publishing my Perl Regex book      **

Reply via email to