in reply to Re: Reopen file when contents changed?
in thread Reopen file when contents changed?
Good!use strict; use warnings;
I think thatwhile()
is more customary. To be fair I thought yours wouldn't have worked at all, but to be sure I tried and it did!while(1)
I, for one (but I'm not the only one!), recommend using the three args form of open. Also, low precedence or is better suited for flow control and you may benefit from including $! in the error message.{ my @loads; my $i = my $cpuload = 0; open(INFIL,"< /proc/stat") || die("Unable To Open /proc/stat\n");
This is overly complex for what it does, IMHO. I would probably do something like<INFIL> =~ /^cpu\s+(\d+)\s+(\d+)\s+(\d+).*/; @loads = ($1, $2, $3);
instead. Of course this is not strictly equivalent to yours. Indeed it may be worth to check that the line is the correct one. In that case you may still do something like this:my @loads = (<$fh> =~ /\d+/g)[0,1,2];
local $_=<$fh>; (warn "something wrong!\n"), next unless /^cpu\b/; my @loads = (/\d+/g)[0..2];
So you want to iterate over the two lists in parallel. Now this is a situation in which some Perl6 features would turn out to be very handy!sleep 1; seek INFIL, 0, 0; <INFIL> =~ /^cpu\s+(\d+)\s+(\d+)\s+(\d+).*/; foreach ($1, $2, $3) { $cpuload += $_ - $loads[$i++]; } close(INFIL);
However, and this is not strictly perl-specific, instead of getting the same info twice per cycle, you may get it once only, and take a "backup" version of it to compare with.
In Section
Seekers of Perl Wisdom