in reply to Simple iteration problem

#!/usr/bin/perl

The next two lines should be:

use warnings; use strict;
open TAB, "test.txt";

You should always verify that the file opened correctly:

open TAB, '<', 'test.txt' or die "Cannot open 'test.txt' $!";
$diff = "$tab[0]" - "$seed";

You are converting the contents of the variables to strings and then subtracting which converts them back to numbers. Just use the variables directly:

$diff = $tab[0] - $seed;
if ($diff ge 0.1)

You are using a text comparison operator on numeric data when you should be using a numerical comparison operator:

if ($diff >= 0.1)
{print "@tab\n" && $seed eq $tab[0]}

The logical AND operator && has relatively low precedence so it is evaluated first and the result of "@tab\n" && $seed eq $tab[0] is passed to the print operator.

{print "@tab\n"; $seed eq $tab[0]}

Replies are listed 'Best First'.
Re^2: Simple iteration problem
by toolic (Bishop) on Nov 29, 2007 at 14:53 UTC
    I agree with much of this. However, i think it should be:
    $seed = $tab[0];
    Etbr77, here is my version (which is nearly identical to AnonMonk's):
    use warnings; use strict; open TAB, '<', 'test.txt' or die "Can not open file: $!"; my $seed = 1.04; while (<TAB>) { chomp; my @tab = split / /; my $diff = $tab[0] - $seed; if ($diff >= 0.1) { print "tab[0]=$tab[0]\n"; $seed = $tab[0]; } } close TAB;
    Since I really have no idea what your input file looks like, I created my own sample input file (test.txt):
    3 5 6 7 2 22 222 10 9
    When I run this script, I get the following output:
    tab[0]=3 tab[0]=5 tab[0]=10
    If this is not what you are looking for, please provide a small sample of your input, and expected output.

    Update: Removed unnecessary else, thanks to Eimi Metamorphoumai.

      I'd just like to add that there's really no reason to include the
      else { next; };
      part, since without it the functionality is exactly the same.
      It works great now! Thank you all very much.
Re^2: Simple iteration problem
by Anonymous Monk on Nov 29, 2007 at 14:49 UTC
    I used your suggestions to create the following script, which is still not quite right. It spits out all of the values in tab[0], whether or not they meet the criterion of the difference in $seed minus $tab[0] being greater than 0.1 I removed the use warnings and strict, just for the moment.
    #!/usr/bin/perl open TAB, '<', 'test.txt' or die "Cannot open 'test.txt' $!"; <TAB>; $seed = 1.04; while (<TAB>){ @tab = split ' '; $diff = $tab[0] - $seed; if ($diff >= 0.1) {print "@tab\n"; $seed eq $tab[0]} else {next}; }
      Gah!!

      I removed the use warnings and strict, just for the moment.
      Why, oh why would you do that?

      <tongue_in_cheek>

      Are you trying to make debugging more "interesting" by hiding clues from yourself?

      If so, don't bother reading about "use diagnostics" which may make debugging even less interesting!

      </tongue_in_cheek>

      ...roboticus