Abhis
Abhis

Reputation: 605

Subtracting an Array form the output Array

I am trying to subtract an array from the output which is an array. I have some set of files in a directory and I need to chech all the files are present in the directory from the list of directory which I mentioned in a array in the script itself. But I am not getting the output.

Here is my script.

#!/usr/bin/perl

use strict;
use warnings;

my $dir = shift || "DIR";
my $pattern = shift || "MY_FILE";
my @files = qw(MY_FILE_JAN_.xls MY_FILE_FEB_.xls MY_FILE_MAR_.xls MY_FILE_APR_.xls MY_FILE_MAY_.xls MY_FILE_JUN_.xls MY_FILE_JUL_.xls);

opendir (DIR, $dir) or die "Failed to open directory\n";
my @files_found  = grep{/^${pattern}_[a-zA-Z]/} readdir(DIR);
for(@files_found){s/[0-9]//g}

my %hash=map{$_ =>1} @files;
my @diff=grep(!defined $hash{$_}, @files_found);

print "$_\n" foreach (@diff);

closedir(DIR);

The list of files which I have in the directory are:

MY_FILE_JAN_201502.xls
MY_FILE_FEB_201502.xls
MY_FILE_MAR_201502.xls
MY_FILE_APR_201502.xls
MY_FILE_JUN_201502.xls
MY_FILE_MAY_201502.xls

Please help or suggest. Thanks in advance.

Upvotes: 0

Views: 50

Answers (1)

ccheneson
ccheneson

Reputation: 49410

It's because at the line

my @diff=grep(!defined $hash{$_}, @files_found);

you are grepping the list of files you have found and since all your files are in @files (and at the same time %hash), @diff will be empty.

What you need is to do the diff according to @files

my %hash=map{$_ =>1} @files_found;
my @diff=grep(!defined $hash{$_}, @files);

Upvotes: 2

Related Questions