Search code examples
perlsubroutine

passing a paramter into a loop perl using a subroutine


i want to read a file1 that containfor every word a numeric reprsentation, for example:

clinton 279
capital 553
fond|fonds 1410

I read a second file, every time i find a number i replace it with the corresponding word. above an example of second file

279 695 696 152 - 574
553 95 74 96 - 444
1410 74 95 96 - 447

The problem in my code is that it execute the subroutine only one time. and it only show:

279 clinton

normally in this example it should show 3 words, when i add print $b; in the subrtoutine it show the different numbers.

#!/usr/bin/perl
use stricrt;
use warnings;
use autodie;

my @a,my $i,my $k;
my $j;

my $fich_in = "C:\\charm\\ats\\4.con";
my $fich_nom = "C:\\charm\\ats\\ats_dict.txt";


open(FICH1, "<$fich_in")|| die "Problème d'ouverture : $!";
open my $fh, '<', $fich_nom;

#here i put the file into a table

while (<FICH1>) {
my $ligne=$_;
chomp $ligne; 


my @numb=split(/-/,$ligne);
my $b=$numb[0];
    $k=$#uniq+1;
    print   "$b\n";
     my_handle($fh,$b);
}

sub my_handle {
    my ($handle,$b) = @_;
    my $content = '';
#print "$b\n";

    ## or line wise
    while (my $line = <$handle>){
    my @liste2=split(/\s/,$line);
if($liste2[1]==$b){
        $i=$liste2[0];
            print "$b $i";}
        }
return $i;
}


    close $fh;
    close(FIC1);

Solution

  • The common approach to similar problems is to hash the "dictionary" first, than iterate over the second file and search for replacements in the hash table:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my $fich_in = '4.con';
    my $fich_nom = 'ats_dict.txt';
    
    open my $F1, '<', $fich_in  or die "Problème d'ouverture $fich_in : $!";
    open my $F2, '<', $fich_nom or die "Problème d'ouverture $fich_nom : $!";;
    
    my %to_word;
    while (<$F1>) {
        my ($word, $code) = split;
        $to_word{$code} = $word;
    }
    
    while (<$F2>) {
        my ($number_string, $final_num) = split / - /;
        my @words = split ' ', $number_string;
        $words[0] = $to_word{ $words[0] } || $words[0];
        print "@words - $final_num";
    }