I have this code which lists all files in my directory:
$dir = '/var/www/corpIDD/rawFile/';
opendir DIR, $dir or die "cannot open dir $dir: $!";
my @file= readdir DIR;
closedir DIR;
which returns an array containing something like this:
$array (0 => 'ipax3_2011_01_27.txt', 1 => 'ipax3_2011_02_01.txt', 2 => 'ipax3_2011_02_03.txt')
My problem here is, how will I store elements 1 => ‘ipax3_2011_02_01.txt’ and 2 => ‘ipax3_2011_02_03.txt’ to separate variable as they belong to the same month and year(2011_02)?
Thanks!
In Perl, when you need to use a string as the key in a data structure, you are looking for the
HASHbuiltin type, designated by the%sigil. A nice feature of Perl’s hashes is that you do not have to pre-declare a complex data structure. You can use it, and Perl will infer the structure from that usage.which prints:
To get at the individual files:
Above I used the return value of the
keysfunction as both the list to iterate over, and as the number of days. This is possible becausekeyswill return all of the keys when in list context, and will return the number of keys in scalar context. Context is provided by the surrounding code:In the last example, each value in
%ipaxis a reference to a hash. Sincekeystakes a literal hash, you need to wrap$ipax{$year_month}in%{ ... }. In perl v5.13.7+ you can omit the%{ ... }around arguments tokeysand a few other data structure access functions.