Is there a way to write a perl subroutine that can read in a file that contains 2 strings on each line and then can create a has with the first string as key and second string as value without using the use the Tie::File::AsHash module ?

use strict;
use warnings;

### Declare you input file location
my $f_path="e:/dani/test1/hash.txt";


### Declare your Subroutine and the file as a argument
my %hash = get_hash ("$f_path");

### print the input file keys and values
print "\n$_ : $hash{$_}" for (keys %hash);

sub get_hash
{
	my ($f_name)=@_;
	my %temp=();

	### File handling and store the data into hash format
	open (FIN, "$f_name") || die "Cannot open the $f_name : $!";
	$temp{$1}=$2 while (<FIN>=~ m/^(.*)\t+(.*?)$/);
	close (FIN);
	
	return %temp;
}

Thank you. I ran the script with my sample text but nothing happened. Am I supposed to input print somewhere else on the script?

I assume your file having keys followed by tab dellimiter and values. If your file having another delimiter modify the below regex part as per your input.

while (<FIN>=~ m/^(.*)\t+(.*?)$/

I assume your file having keys followed by tab dellimiter and values. If your file having another delimiter modify the below regex part as per your input.

while (<FIN>=~ m/^(.*)\t+(.*?)$/

Thank you for the help and I made the correction but when I run the script it is still saying "Press any key and continue". The text on my file has text that reads:

Cameron name
square shape
dinosaur animal
age 100

Does that make a difference?

Could you show the code ?

Hi Makailah, The code posted by manimuthu is GREAT!!. but a small correction u should do.

and the revised code is

use strict;
use warnings;

### Declare you input file location
my $f_path="e:/dani/test1/hash.txt";


### Declare your Subroutine and the file as a argument
my %hash = get_hash ("$f_path");

### print the input file keys and values
print "\n$_ : $hash{$_}" for (keys %hash);

sub get_hash
{
	my ($f_name)=@_;
	my %temp=();

	### File handling and store the data into hash format
	open (FIN, "$f_name") || die "Cannot open the $f_name : $!";
	$temp{$1}=$2 while (<FIN>=~ m/^(\S+)\s+(.*?)$/);
	close (FIN);
	
	return %temp;
}

Thanks and Regards,
yuvanbala

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.