#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2017
    Posts
    2
    Rep Power
    0

    how to write results in file perl


    hello ,

    i have a script that read 2 fils the first is a dictionnary like this
    1 car
    2 home

    the second is like this
    1 2
    2 2

    the script replace number in the second file with string thar correspond so the resulat is like this
    car home
    home home

    my probleme thar i want to save results in a new file

    Code:
    help !
    #!/usr/bin/env perl
    use strict;
    use warnings;
    use autodie;
     
    open (my $fh, "<", "file1.txt" );
    my %hash;
    while (<$fh> ) {
        if (/^\s*(\d+)\s+(.*\S)\s*$/) {
            $hash{$1}=$2;
        }
    }
    close $fh;
    
    open ($fh, "<", "file2.txt" );
    while (<$fh> ) {
        if (/^\s*((\d+)\s+)*\d+\s*$/) {
        my @line = split(/\s+/, $_);
        foreach (@line) {
            print $hash{$_}, " ";
        }
        print "\n";
        }
    }
    close $fh;
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2017
    Location
    Minnesota, USA
    Posts
    13
    Rep Power
    0
    The code you have will produce the output on your terminal, but I'm guessing that's not what you want. Another option would be
    to redirect the output on the command line, such as ./mycmd.pl > file3.txt. Again, that doesn't appear to be your goal.

    In order to do this within the program, create another file handle with 'open my $fhout, ">", "file3.txt";' (side note: You might want
    to add an 'or die "message"' to your opens, to allow for the input files not existing and such. Your call.) Then, on your print calls,
    change them to 'print $fhout $hash{$_}, " ";'. Note that there is no comma between $fhout and what is to be printed.

IMN logo majestic logo threadwatch logo seochat tools logo