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

Good morning monks! I'm hoping that posting my issue here someone will be able to point me in the right direction.

I believe myself to be a fairly competent bash coder, and I'm starting to take on perl as my new language (and I'm loving it so far). I am having trouble with a piece of code that I'm working with, and I was hoping to find someone that could point me in the right direction.

my $hours; open( SMRT, "/root/perk/tmpfile" ); while( <SMRT> ){ chomp (); if (/Power_On_Hours(.*)/i) { $hours = $1 ; } @time = split(' ',$hours); print "Power on hours = $time[7]\n"; } close(SMRT);
tmpfile is a smartctl output. The line I'm trying to capture is:

9 Power_On_Hours 0x0032 099 099 000 Old_age Always - 916

My thinking about it, is that I should put that line into a variable, than split it with spaces into an array and call the last line by $time[7], which should return "916".

However when I'm running it, it's doing something crazy:

Power on hours = --snipped, above repeats 20 times-- Power on hours = 916 --snipped, above repeats 20 times--

I would greatly appreciate the wisdom from anyone who can point me in the direction I need to go.

Replies are listed 'Best First'.
Re: Pulling lines from file, noob style
by toolic (Bishop) on Feb 17, 2010 at 17:28 UTC
    Obviously, since you only showed 1 line of your input, this is just a guess, but perhaps you really want to only print if the regex matches, something like this:
    while( <SMRT> ){ chomp (); if (/Power_On_Hours(.*)/i) { $hours = $1 ; @time = split(' ',$hours); print "Power on hours = $time[7]\n"; } }
    Also, use strict and warnings, as they would probably have given you some useful debugging information in this case.
      Yes! That did it! It looks like I closed that expression early than? Is that why it picked up more than what I asked?

        It picked up exactly what you asked, but it printed even when it didn't pick anything up. as you use Perl, your mind will assimilate to a more perlish way of procedural thinking. for instance, the same snippet could be written as

        while( <SMRT> ){ chomp; next unless /Power_On_Hours(.*)/i; $hours = $1; @time = split(' ',$hours); print "Power on hours = $time[7]\n"; }

        although the overall effect is the same as using an if statement the intention is more explicit: you don't care about the line unless it matches the regex. as perl takes over you mind, you should notice a decrease in errors of this sort


        $,=qq.\n.;print q.\/\/____\/.,q./\ \ / / \\.,q.    /_/__.,q..
        Happy, sober, smart: pick two.