Faz said:
I have a text file in a single column which has name address, phone
age of each people as below
Name
Address
phone
age
Name
Address
phone
age
I want to put all the names in the names array, all the address in
address array all the phone in the phone array etc
Why four different arrays? A single array of arrays or array of hashes would make more sense.
A simple example (untested):
open IN, 'text_file' or die "Cannot open text_file: $!";
my ( @names, @addresses, @phones, @ages );
until ( eof IN ) {
chomp( my $temp = <IN> );
push @names, $temp;
chomp( $temp = <IN> );
push @addresses, $temp;
chomp( $temp = <IN> );
push @phones, $temp;
chomp( $temp = <IN> );
push @ages, $temp;
}
close IN;
for my $index ( 0 .. $#names ) {
print "Name: $name[$index]\n";
print "Address: $addresses[$index]\n";
print "Phone: $phones[$index]\n";
print "Age: $ages[$index]\n\n";
}
Or with an array of arrays:
open IN, 'text_file' or die "Cannot open text_file: $!";
my @data;
until ( eof IN ) {
push @data, [ grep chomp, map scalar <IN>, 1 .. 4 ];
}
close IN;
for my $record ( @data ) {
print "Name: $record->[0]\n";
print "Address: $record->[1]\n";
print "Phone: $record->[2]\n";
print "Age: $record->[3]\n\n";
}
Or with an array of hashes:
open IN, 'text_file' or die "Cannot open text_file: $!";
my @data;
my @fields = qw/Name Address Phone Age/;
until ( eof IN ) {
@{ $data[ @data ] }{ @fields } = grep chomp, map scalar <IN>, 1 .. 4;
}
close IN;
for my $record ( @data ) {
for my $field ( @fields ) {
print "$field: $record->{$field}\n";
}
print "\n";
}
John