![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrrUJet9lruhHu-Vy3y7Eeom89unqd3bcX2syPALzZLocxqDKG4tzZtU8R1KbRW-2ZuJKRMhcvU5DN1Q6O4PkDyIrjpVTH77f-Sp8jMPDFmW2gKle3jy2CdPBNrSg4Rx0Bb6aFBZfZOVg/s1600/perl_logo2.gif)
Most of the time, we want to achieve a REAL-TIME processing. However, there are some limitations that we don't have control over, and one of the best example is without having a direct connection to the application you are processing into.
One way to achieve a REAL-TIME processing without a direct connection is to have a back-end processing that will watch and process transactions. This is what we called directory watcher.
With this post, it will help you create a directory watcher in PERL. Just follow the simple steps below to do that.
1. Set the look up directory where you want your script to look into.
2. Create a NON-ENDING loop using WHILE() syntax. To create a NON-ENDING loop, we just have to pass a variable or condition that will always results to TRUE. Example below pass a variable 1 that results to TRUE. And as best practice, a SLEEP function should be implemented every end of each loop, this is for the script not to eat too much of the memory.
while(1) {
# this creates a non ending loop coz 1 is equal to true..
sleep 1;
}
3. Inside your WHILE loop, you have to OPEN the look up directory by using OPENDIR() syntax. And as best practice, you need to close the directory every end of the loop.
opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
4. Loop the files we read from a look up directory.
opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
while ($file = readdir(DIR))
{
# file names from a reading directory...
}
closedir DIR;
Hope you like it!! Please see the complete code below for your implementation.
#!/usr/bin/perl
$lookup_dir = "<directory to look into>";
while(1)
{
print "lookup directory: $lookup_dir\n";
opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
while ($file = readdir(DIR))
{
if (($file ne '.') && ($file ne '..') && ($file !~ /^\./))
{
print "here file: $file\n";
# do what you want with the file...
}
}
closedir DIR;
sleep 1;
}
1;
No comments:
Post a Comment