Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

One more...reading a file into an array/hash 2

Status
Not open for further replies.

jtb1492

Technical User
Mar 17, 2005
25
US
I have a text file. 1 column, all numbers. I want to read the number on each row into an array. Isn't there some simple way to do it without a counter? something lie @myarray = <>; or something?


What if there were two column in the data files, and the first way the key value.

Thanks for all the help guys!
 
How about:
[tt]
open F,'<c:/temp/test.txt';
chomp (@a=<F>);
close F;
[/tt]
 
Cool. What if there are two columns in the text file and I want the first one to be the values of the array. How do I encorporate the split command?
 
Sorry, I missed that bit.
You could use something like:
[tt]
open F,'<c:/temp/test.txt';
for(<F>)
{
chomp(@a=split / /,$_); # assuming space as the separator
$hash{$a[0]}=$a[1];
}
close F;
[/tt]
%hash then contains the values read.
 
Or like this:
Code:
#!perl
use strict;
use warnings;

my %h = map {chomp; split} <DATA>;
print "$_ => $h{$_}\n" for sort keys %h;

__DATA__
A 1
B 2
C 3
D 4
E 5
Output:
Code:
A => 1
B => 2
C => 3
D => 4
E => 5
If you wanted the second value on each line to be the key and the first the value, you could just apply the reverse function to the result of the split, like so:
Code:
my %h = map {chomp; [b]reverse[/b] split} <DATA>;
Output:
Code:
1 => A
2 => B
3 => C
4 => D
5 => E


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top