herny has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am new with Perl, and I am getting a little crazy trying to solve a problem with files (that is maybe trivial). I have two files in the form of columns separated by tabs, one with my data (IDs and numbers assigned to these IDs) and the other one with IDs conversions. I need to substitute the IDs in my data file for the other IDs. For example, my data file is like this: ID number \n house 325 \n car 1456 \n table 2489 \n ... And the conversion file is: car opel \n house flat \n table wood \n ... What I want is something like this: ID number flat 325 opel 1456 wood 2489 ... I am going over through many tutorials but I am quite lost, I don't know how even start. Can someone help me? Many thanks, Herny

Replies are listed 'Best First'.
Re: file handling
by toolic (Bishop) on Jun 07, 2010 at 16:32 UTC
    I don't know how even start.
    Rather than providing a full solution, I will give you an algorithm, and start you on the first step.
    • Read your conversion file into a hash.
    • Loop through your data file line-by-line.
    • Split it into tokens.
    • Match the ID to a key of the hash.
    • Print it out in the format you desire.
    use strict; use warnings; my %conv; open my $fh, '<', 'conv.txt' or die "can not open conv.txt\n"; while (<$fh>) { chomp; my ($k, $v) = split; $conv{$k} = $v; } close $fh;
    Try to understand that code, then ask questions if necessary. If you already know how to open files, then post the code you have so far, and post the actual output you are getting if it differs from your expected output.

    Have you looked at the official Perl documentation yet? perlintro

    In the future, post your data inside code tags. Refer to Writeup Formatting Tips.

Re: file handling
by choroba (Cardinal) on Jun 07, 2010 at 16:42 UTC
    If you are under linux or similar OS, you may just use the join utility. In such a case, the files must be sorted and IDs must be unique, though.