Extracting and storing the the values in key value pair from a text in file in perl

Viewed 539

I have a text file like which contains information like this:

name=A
class=B
RollNo=C

I want to extract the values in perl script

key(name) = value(A)
key(class) = value(B)
key(RollNo) = value(C)

the keys should be exported as the variables which will have values. Whenever we type

print $name

the output should be 'A'

I have tried:

open my $fh, '<', $file_name
  or die "Could not open sample.txt: $!";
my @lines = <$fh>;

my %hash;
while (<@lines>) {
    chomp;
    my ($key, $value) = split /=/;
    next unless defined $value;
    $hash{$key} = $value;
}
print %hash;
3 Answers

Your code looks pretty good and most of what you've done so far works.

At the end, you run print %hash and that doesn't give you what you expect. That will "unroll" the keys and values from the hash into a list and print that list. So you get all of the keys and values printed out.

If you just want one value (for example, the value associated with the "name" key), then just print that.

print $hash{name};

Is that what you were looking for?

You could try using one of the configuration modules that are available. Config::Tiny seems to fit your data:

use strict;
use warnings;
use Data::Dumper;
use Config::Tiny;
 
my $Config = Config::Tiny->new;
 
$Config = Config::Tiny->read( 'a.txt' );   # your text file name goes here

print $Config->{_}{name};                  # print the name value
print Dumper $Config;                      # print all the values in perl variable format

You can store data in hash and can retrieve from their.

use strict;
use warnings;

use Data::Dumper;

my %hash = (
    name    => 'A',
    class   => 'B',
    RollNo  => 'C'
);

print Dumper(\%hash);

print $hash{'name'};
Related