简体   繁体   中英

how to print all the lines of a text file from hash - perl

I am reading a text file which is having multiple lines in it. I have been assigned a task to print the lines using hash.

"\n" is the delimiter we can use.

Here is what I tried and got stuck :

code :

use strict;
use warnings;

my %hash = ();
my $key;

open (my $fh , "<","test.txt") or die "can not open the file $!\n";

while (my $line =<$fh>)
{
    chomp ($line);
    my($key, $number) = split("\n", $line)
    $hash{$key} = [ $count, $number ];
} 

i am not able to understand what will be my key in the hash. Can some one help me out to resolve the issue.

You have

while (my $line =<$fh>)

which reads a single record via $fh . The default input record separator in Perl is "\\n" meaning you are reading the file line-by-line. By definition, a single line has a single line-terminator.

chomp ($line);

then removes this single "\\n" from the string in $line .

Therefore,

my($key, $number) = split("\n", $line);

copies $line to $key , and leaves $number undefined as there is no "\\n" in $line . Even if you had not chomp ed the line, $number would not contain anything useful because the line-terminator, by definition, would be at the end of the line and there would be nothing after it by virtue of the fact that it marks the end of the line.

If the file contains something along the lines of:

key1
value1
key2
value2

then you can read those one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM