Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: how to remplace a names in a file by keys with hash

by Cristoforo (Curate)
on Apr 27, 2018 at 22:21 UTC ( #1213710=note: print w/replies, xml ) Need Help??


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:

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1213710]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2021-04-14 17:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?