This is regarding the behaviour of the function in Perl.
Code Snippet:
&mmg();
my $count;
sub mmg {
&kkg();
print "symlink at location updated with the value\n";
$count ;
print "$count is value of count \n";
}
sub kkg {
if (-d "/home/PPP/ee/dir1") {
print "I got dir1\n";
my @arr = glob ("/home/PPP/YEP");
#..
#..... Some more commands
#..
return;
}
else {
sleep 5;
&mmg();
}
}
Output:
symlink at builds location updated with the value of link at builds location
1 is value of count
symlink at builds location updated with the value of link at builds location
2 is value of count
symlink at builds location updated with the value of link at builds location
3 is value of count
symlink at builds location updated with the value of link at builds location
4 is value of count
symlink at builds location updated with the value of link at builds location
5 is value of count
symlink at builds location updated with the value of link at builds location
6 is value of count
Here, "dir1" was not there, and I created after 30-35 seconds. Now, as per my understanding, after 30-35 sec (when dir1 was created), only "symlink at builds location updated with the value of link at builds location \n 1 is value of count" should have come i.e. only once these statements would have printed. But, why are these being printed multiple times?
Can anyone please help me understand the concept as per the output behaviour? And how can I let this print statement be printed just once?
Concept of my understanding: mmg() will call kkg(), and it will see if dir1 is present or not. If not, sleep 5 and then again call mmg(). mmg() will again call kkg(), and so on until dir1 is present. And if dir1 is available, kkg() will be returned, and mmg() proceeds further and print content inside just once.
Thanks!
CodePudding user response:
This is the execution of your code:
&mmg();
&kkg();
if ...
else mmg();
&kkg();
if ...
else mmg();
&kkg();
if found! return to mmg()
print 1, sub finishes
print 2, sub finishes
print 3, sub finishes
Because each time your check if dir1 exists, you start a new mmg() process, and each of those processes will print once before finishing. Because they are nested into each other.
What you should do is to just use kkg() as a boolean, and let mmg() handle the loop control, e.g.:
sub mmg {
while (!kkg()) {
sleep 5; # do nothing
}
print "....";
# done
}
sub kkg {
if (-d "/home/PPP/ee/dir1") {
# do stuff
return 1; # true
}
return 0; # false
}
You may not even need kkg().
Also, you should be aware that the sub calling method you use -- &NAME()
-- is not the idiomatic one. In perldoc perlsub you can read this about the different ways a subroutine can be called:
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME; # Makes current @_ visible to called subroutine.
You should use NAME()
.