0

There is a dynamic file which will be generated before my script executing.

my $file = a.txt;

Here i want to check:

(Is content of $file changed)? Do_something: Skip;

I'm looking for some solution as below:

  • if ( if_modified( $file );

    --> But We need an initialization file and compare with the latest file while here we have only 1 file at a time.

  • $monitor->watch( $file ); Is it able to do my task?

  • I guess that using checksum is not needed because after that i also need to see if checksum result is changed or not.

  • 1
    "Has file changed" needs to specify since when. See also [Linux::Inotify2](http://p3rl.org/Linux::Inotify2). – choroba Sep 24 '18 at 08:29

2 Answers2

2

There are a few possibilities:

And Linux-specififc:

as mentioned by @choroba

JGK
  • 3,710
  • 1
  • 21
  • 26
2

The Perl file operators and the stat function also tell you when a file was last changed (it's modification time) . The common approach is to check against some reference file, that is whether a file was changed later than the reference file, or to check when a file was changed relative to the script start.

Get the time when a file was last modified

my $last_modified = (stat $filename)[9];

if( $last_modified >= $other_modified ) {
    # file changed since we last checked ...
    $other_modified = $last_modified;
};

Check if a file was modified some days ago:

if( -M $filename > 5 ) {
    print "'$file' was modified at least 5 days ago\n";
};

See also

stat , the -M function

Corion
  • 3,855
  • 1
  • 17
  • 27
  • Thank you very much for your suggestion. But with this, how could we define the $other_modified to be used in if command? Is there any other solution to check the changing of content only? – Hung Nguyen Sep 26 '18 at 08:33
  • You can initialize the value of `$other_modified` the same way: `$other_modified = (stat $filename)[9]` . You haven't told us enough about what your program needs to do , so we can't make good suggestions to your program logic flow. – Corion Sep 26 '18 at 11:48
  • With this initialzation, both of $other_modified and $last_modified will be initialized with the same value. It cause the if condition will always got true. Isn't it? – Hung Nguyen Sep 26 '18 at 15:05
  • Both values will start out the same, but if time passes and the file gets modified in between, the values will differ, which is (I think) what the OP wants – Corion Sep 27 '18 at 06:46
  • Hmm i don't think so. I think the if() condition always got true and code inside if{} will execute whenever this script is called. – Hung Nguyen Sep 27 '18 at 12:07
  • ... unless of course the `if` condition is in a loop like `while( 1 ) { my $last_modified = (stat $filename)[9]; if( $filename >= $other_modified ) { print "Modified\n"; $other_modified=$last_modified }; sleep 60 }` – Corion Sep 27 '18 at 12:31