Perl Reading into Hash





You've already seen that you can read a file directly into a regular array using this syntax:
@array = ;
Unfortunately, there is no similar way to read an entire file into a hash. But, it's still pretty easy to do. The following example will use the line number as the hash key for each line of a file.
Reading a Fixed Length Record with Fixed Length Fields into a Hash
open(FILE, "fixed.dat");
while(){
$hash{$.}=$_;
}
close(FILE);
foreach(keys(%hash)){
print("$_:$hash{$_}");
}
This program displays all the lines in the file fixed dat, prefixed with the line number. Few examples illustrating the use of open function.
Example 1 : open (IN, "> data dat") or die ("sorry");
for ($i=O, $i<=5, $i++)
{
print IN "$i\n;
}
close (IN);
This program create a file data dat in which the contents will be 0 1 2 3 4 5
Example 2:
Open (ln,'< data.dat) or die (sorry);
while ()
{Sn = $_;
print $n;
}
close (IN)
This programs reads the file data.dat and print its contents
0
1
2
3
4
5
Domain Name Search
|