jsdlkjalsd same_text = 1, jhhj, jhjk = 256, iuqoi, uereoiu, sjksdh, same_text = 2, lkkj, lksj = 6287 uwie same_text = 2, sdaj, jsdgd, sksd #### For the key "1" the value should be "jhhj, jhjk" For the key "2" the value should be "lkkj, lksj , sdaj, jsdgd" #### use Data::Dumper; open(FH,"x.txt") or die("Can't open the file: $!"); $/=EOF; my $var = ; my %hash=(); while ($var =~ /(same_text\s=\s\d),((\s\S+){1,2})/gi) { my ($junk,$ky)=split(/=/,$1); push(@{$hash{$ky}},$2); } map { print "$_ -- @{$hash{$_}} \n "; } keys %hash;