LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Reading lines from files Perl (http://www.linuxquestions.org/questions/linux-newbie-8/reading-lines-from-files-perl-874937/)

jack.barnes 04-14-2011 03:51 AM

Reading lines from files Perl
 
Hi All,

The code below is currently reading any line that does not meet my criteria (which is working fine). Instead of printing the line that is incorrect (which it currently does) I wish for it to print the line above it from the file instead of the actual line (the line above has the name which is valuable to the user)

Code:

use Getopt::Long;
use warnings;
use strict;

open my $input, "mirror_status_data";

my $broken_line = '';
my $all_ok=1;

while (<$input>){

    if ( $_ =~ /V Status/ && $_ !~ /available(\/syncd)?$/ ){
        $broken_line = $_;
        $all_ok=0;
        print "badline: $broken_line";
    } 
};

if ($all_ok==0) {
    print "CRITICAL \n";
  # print "badline: $broken_line";
}
else{
    print "OK \n";
}

close $input;

Any Suggestions?

brownie_cookie 04-14-2011 04:19 AM

i'm not familiar with Perl so don't be mad if it doesnt work, but sometimes i need something like you are using (but then in another programming language) and then i do "-1"
i geuss you got to do something like:
Code:

while (<$input>){

    if ( $_ =~ /V Status/ && $_ !~ /available(\/syncd)?$/ ){
        $broken_line = $_ -1;
        $all_ok=0;
        print "badline: $broken_line";
    } 
};

I really don't know if that's possible
or the thing that you put in $broken_line is that a word or a number ?

bsat 04-15-2011 03:14 AM

I don't know a perl specific solution but here is something that might work
Code:

while (<$input>){


    if ( $_ =~ /V Status/ && $_ !~ /available(\/syncd)?$/ ){
        $broken_line = $_;
        $all_ok=0;
        print "badline: $prev_line";
    } 
$prev_line = $_
}


grail 04-15-2011 04:05 AM

There is probably a Perl-centric solution, but brownie's idea and bsat's solution is the way I would go.
Basically you store the previous line on each iteration of the file and when your if is true you print the last stored value.


All times are GMT -5. The time now is 03:38 PM.