On Sun, 8 Sep 2002, pn wrote:
> Hi,
>
> I have a file age_classes.txt in /prj/tmp that
> contains the following information. These are intended
> to be prefixes for the file names in the agegroup_data
> directory.
>
> $ cat $age_classes.txt
> agegroup2
> agegroup3
> agegroup4
>
> I also have a directory /prj/temp/agegroup_data that
> contains the following files:
>
> agegroup2ha0.txt
> agegroup2hb0.txt
> agegroup2hc0.txt
>
> agegroup3ha0.txt
> agegroup3hb0.txt
> agegroup3hc0.txt
> agegroup3hd0.txt
>
> agegroup4ha0.txt
> agegroup4hb0.txt
> agegroup4hc0.txt
> agegroup4hd0.txt
> agegroup4he0.txt
>
>
> What I am trying to do is the following:
>
> 1) open and read each line of the age_classes.txt file
> 2) for each entry in the age_class.txt file, find all
> the matching files the /prj/tmp/agegroup_data
> directory, and store it in an array.
> 3) Print the contents of the array to a file
>
>
> Here is the code that I have, but it does not seems to
> do what I want. I think the problem is with the way
> that I am doing the file globbing. Would greatly
> appreciate your help in understanding what is the
> correct way to do this.
>
> Thanks
>
> PN
>
>
>
> #!/usr/bin/perl -w
> use strict;
>
>
> my $Wdir = "/prj/temp/";
> my $age_class_file = "$Wdir/age_classes.txt";
>
> open (IN,"<$age_class_file") || die " Required
> Input file : $age_class_file not
> Found\n\t\t\t........Aborting\n" ;
>
> while (<IN>) {
>
> my $tmp_var;
> my @age_class_list;
> my $age_group;
>
>
> chomp;
> # remove newline characters
> $tmp_var = "$_"."*"."\."."txt";
> $_ = "$Wdir/agegroup_data/$tmp_var";
> @age_class_list = $_; #
> capture input lines and store in an array variable
> print "@age_class_list\n";
>
Where have you done the globbing? At this point @age_class_list is an one
element array, the element being "/prj/temp/agegroup_data/agegroup2*.txt".
> foreach $age_group (@age_class_list) {
> open (DATA_OUT,
> ">$Wdir/age_groups_output_list.txt") || die " Could
> not Open output file ....Aborting";
Two points here
1) You are opening the file for writing inside the foreach loop. In this
case since it will always be a single element array it is fine. But the
open should be above the loop.
2) When you open the file with a ">" before the filename it will be
truncated and opened for output. You need to open with ">>" for appending.
> print DATA_OUT $age_group;
> }
> close DATA_OUT;
> }
> close IN;
An easier way to do this
#!/usr/local/bin/perl -w
use strict;
my $Wdir = '/prj/temp';
my $age_class_file = "$Wdir/age_classes.txt";
open (IN, $age_class_file) or die "$!\n";
while (<IN>) {
chomp;
open (DATA_OUT, ">>$Wdir/age_groups_output_list.txt") or die "$!\n";
foreach my $file (<$Wdir/agegroup_data/$_*.txt>) {
print DATA_OUT "$file\n";
}
print DATA_OUT "\n";
close (DATA_OUT);
}
close (IN);
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]