In my program I am passing a list of file names from command-line to my program, and checking whether each file is – executable, readable and writable..
I am using foreach-when statement for the above problem.. But there seems to be some problem in the use of when and default statements, which may be I’m not using correctly, but its giving me unexpected result..
Here’s my code: –
#!/perl/bin
use v5.14;
use warnings;
foreach (@ARGV) {
say "*************Checking file $_ *******************";
when (-r $_) { say "File is Readable"; continue; }
when (-w $_) { say "File is Writable"; continue; } # This condition is true
when (-x $_) { say "File is Executable" } # This condition is false
default { say "None of them" } # Executed
}
I have added a continue, only to the first two when to make perl check for all the conditions regardless of the name of the file..
Also, I haven’t added a continue to the second last when, because I only want my default to be executed if none of the when is executed..
The problem here is, if the last when condition is false, it will not enter the block, and then it goes on to execute the default even though my first two when statements are satisfied.
I checked the reason of this problem by changing the order of my when, and saw that if only the last when is executed, it will see that there is no continue, and hence it will not execute the default statement..
So, in the above code, I have swapped -x and -r.. My file is readable, so last when in this case will be executed.. And then my default statement is not executed..
#!/perl/bin
use v5.14;
use warnings;
foreach (@ARGV) {
say "*************Checking file $_ *******************";
when (-x $_) { say "File is Executable"; continue; }
when (-w $_) { say "File is Writable"; continue; }
when (-r $_) { say "File is Readable" } # This condition is true
default { say "None of them" } # Not executed
}
So, I want to ask, how to handle these kinds of situation.. I want it to work like the way for which given-when statement was added to Perl..
It should check all the when, and skip the default if at least one when is executed..
Since
defaultisn’t an “else condition” but can be seen as a when that always matches, it’s not really a good match for what you’re trying to do. In your default condition, you don’t know anything about earlier matches in that block, and you can’t break out of the topicalizer earlier without knowing if any laterwhenwill match, so either you have to “hack it” with a boolean that says one of the earlier matched, or just exchange it for a when that takes care of the “left over” condition;