in reply to how to remplace a names in a file by keys with hash
Hello
Your program is full of errors, some of which would have been caught if you had at the top of your program:
Rather than going through your program to note the errors and some useless statements, I will post a correct program and you will see how it should look.use strict; use warnings;
Note that it does not loop through the keys like you do. And it only opens the file for reading once (the main loop).#!/usr/bin/perl use strict; use warnings; my %lista2 = ( 1 => "CAT00.3", 2 => "CAT43.1", 3 => "CAT40.3" ); # open filehandle for reading (check that open was successful or die) open my $AL, '<', 'file.txt' or die $!; # open filehandle for writing (check that open was successful or die) open my $OA, '>', 'file2.txt' or die $!; while (my $line = <$AL>) { if ($line =~ /^>(\d+)$/) { my $key = $1; if (exists $lista2{$key}) { $line =~ s/$key/$lista2{$key}/; } } print $OA $line; } close $AL or die $!; close $OA or die $!;
As for what's inside your while loop, there doesn't seem to be any reason for the different actions you have taken. Most don't make sense.
Instead of using the default variable '$_' to read in the input in the while loop, I assigned the line being read to '$line' and this was just for clarity for this example. If I were writing the program myself, I would've probably relied on the default variable '$_' instead.
Since I am using 'strict', I have to declare all the variables (with my ...) when they are first mentioned.
In Section
Seekers of Perl Wisdom