Hello

Your program is full of errors, some of which would have been caught if you had at the top of your program:

use strict; use warnings;
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.
#!/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 $!;
Note that it does not loop through the keys like you do. And it only opens the file for reading once (the main loop).

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 reply to Re: how to remplace a names in a file by keys with hash by Cristoforo
in thread how to remplace a names in a file by keys with hash by zelman796

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.