Reputation: 59
I have list2.txt file and inside that file, there are several files like 02x5.txt
or 0.3x5.txt
etc. Then how to read data inside 02x5.txt
file at one time? Inside 02x5.txt
, there are height:20, length:5, colour:blue
etc.
inside list2.txt:
02x5.txt
03x5.txt
inside 02x5.txt:
height:20,
length:5,
colour:blue
inside 03x5.txt:
height:25,
length:10,
colour:green
#!/usr/bin/perl
use strict;
use warnings;
# Reading a line from a file (or rather from a filehandle)
my $filename = "list2.txt";
if (open my $data, "<", $filename) {
while (my $row = <$data>) {
chomp $row;
if ($row =~ m/02x5.txt$/ ){
my $m = $row;
print "$m\n";
}
}
}
How can I read data for height and length from certain txt file? Thank you
Upvotes: 1
Views: 71
Reputation: 69224
The answer is always to break the problem down into smaller chunks.
#!/usr/bin/perl
use strict;
use warnings;
my @files = get_list_of_files();
my %data;
foreach my $file (@files) {
my $file_data = get_data_from_file($file);
$data{$file} = $file_data;
}
# You now have your data in a hash called %data.
# Do whatever you want with it.
sub get_list_of_files {
open my $list_fh, '<', 'list2.txt'
or die $!;
my @files = <$list_fh>;
chomp(@files);
return @files;
}
sub get_data_from_file {
my ($filename) = @_;
my $record;
open my $fh, '<', $filename or die $!;
while (<$fh>) {
chomp;
# Remove trailing comma
s/,$//;
my ($key, $value) = split /:/;
$record->{$key} = $value;
}
return $record;
}
Upvotes: 0
Reputation: 6798
Please see following piece of code which performs tasks you've described, read data stored in hash %data
which you can use anyway you desire.
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
my $debug = 1;
my $filename = 'list2.txt';
my %data;
open my $fh, '<', $filename
or die "Couldn't open $filename";
my @filenames = <$fh>;
close $fh;
chomp @filenames;
foreach $filename(@filenames) {
open $fh, '<', $filename
or die "Couldn't open $filename";
while( <$fh> ) {
chomp;
my($k,$v) = split ':';
$data{$filename}{$k} = $v;
}
close $fh;
}
say Dumper(\%data);
Output
$VAR1 = {
'02x5.txt' => {
'colour' => 'blue',
'height' => '20, ',
'length' => '5, '
},
'03x5.txt' => {
'length' => '10, ',
'colour' => 'green',
'height' => '25, '
}
};
Upvotes: 2