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

I have a script which is reading from a file and i am assigning a variable a value from an element in an array produced during script. I want a section of the script to run only if that value of that element of the array changes , if it does not not i want it to return to the start
while ($line=<In>) { @temp = split(/[=]/,$line); if ($temp[1] >100) { print "Session id: $temp[1] "; $sessid = $temp[1]; } #I want the following to run only if $sessid changes $modtyp = $temp[1]; if($modtyp == 20) { print " V34\n\n "; } elsif ($modtyp == 9) { print " no connection\n\n"; }

Replies are listed 'Best First'.
Re: runnig part of script when variable changes
by vek (Prior) on Feb 21, 2002 at 13:49 UTC
    First of all, use strict and -w or warnings.

    Now to the problem at hand. You don't give many specifics so the following code just checks to see if the value of $temp[1] changes from line to line in your file:
    my $firstLineFlag++; my $sessid; while (my $line = <IN>) { my @temp = split (/[=]/, $line); if ($temp[1] > 100) { print "Session id: $temp[1] "; } if ($firstLineFlag) { $sessid = $temp[1]; $firstLineFlag = ''; } if ($temp[1] ne $sessid) { if ($temp[1] == 20) { print " V34\n\n "; } elsif ($temp[1] == 9) { print " no connection\n\n"; } $sessid = $temp[1]; } }
      I am getting the error " can't increment in my at var.pl line x, near "++;"
        Really? Please post your code. I'm assuming the offending line is the my $firstLineFlag++; line which (if used as I posted) will just set the value of $firstLineFlag to 1.
Re: runnig part of script when variable changes
by splatohara (Novice) on Feb 21, 2002 at 17:33 UTC
    here is the code
    #!/perl/bin open (In,"tascomod.log") or die ("an not open file at the moment"); open (Out, "tasmodtypfinrpt.txt") or die ("cannot open output file may +be you sho uld create one"); print "\n\n Session id Modulation \n\n"; my $firstlineFlag++; my $sessid; while (my $line = <IN>) { my @temp = split (/[=]/, $line); if ($temp[1] > 100) { print "Session id: $temp[1] "; } if ($firstLineFlag) { $sessid = $temp[1]; $firstLineFlag = ''; } if ($temp[1] ne $sessid) { if ($temp[1] == 20) { print " V34\n\n "; } $sessid = $temp[1]; } }
      If you'd had 'use strict' at the top of the script you'd have spotted that '$firstlineFlag' is not the same as '$firstLineFlag'. Also the declaration of '$firstlineFlag' increments an uninitialised variable (which would have been caught with '-w'). Once it runs cleanly with 'strict' and 'warnings', you'll be in a better position to find out what the problem is with your algorithm. (I suspect that it will be OK when '$firstlineFlag' is changed to '$firstLineFlag').

      rdfield