Can you explain me how to check if an element belongs to array? My script needs to know whether the element has wanted extension to make a shortcut and copy it to another directory.
Here is an example:
my @array = qw(avi mp4 mov);
my $dir = "E:\Downloads";
opendir (my $dh, $dir);
while (my $file = readdir($dh))
{
if($file ~= )
instructions...
}
There is a solution in perlfaq4, section "How can I tell whether a certain element is contained in a list or array?" here: http://perldoc.perl.org/perlfaq4.html#How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array ?
If you are using Perl 5.10 or newer, the solution is:
if( $item ~~ @array ) {
say "The array contains $item"
}
Please have a look at the link if you have an older Perl. There is other possibilities as well.
Regarding you task: if you just want to search a folder for files having a certain extension, I can recommend using File::Find::Rule :
# find all the .pm files in @INC
my @files = File::Find::Rule->file()
->name( qr/\.(?:avi|mp4|mov)$/ )
->in( $dir );
You can use grep to go through the array one at a time and see if any match:
if ( grep $file ~= /\Q.$_\z/, @array ) {
Or join the array elements into a single regex:
my @array = qw(avi mp4 mov);
my $selected_extensions = qr/^\.(?:@{[ join '|', map quotemeta, sort @array ]})\z/;
my $dir = "E:\Downloads";
opendir (my $dh, $dir);
while (my $file = readdir($dh))
{
if($file ~= $selected_extensions)
instructions...
}
In your case you can write
while ( my $file = glob 'E:\Downloads\*.{avi,mp4,mov}' ) {
# Process $file
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.