简体   繁体   中英

Join two files (tables) in perl

I want to join two files in one using perl. More specifically:

I have one txt file with columns:

Irrelevant / Key / Various1 / ... / Various N

and a second txt file with columns:

Key / Price

I want to read the two files and join them so that I have:

Key / Various1 / ... / Various N / Price 

for all lines of the first table. How can I do it? I have little experience.

I need either a table ( hash ?) that I can then process further in my script or a new file that I can then read and do the rest of the process.

Any help will be appreciated.


thanks for the irony... I already said that I have no experience and I dont know how ahshes work which seem to be the solution... I found this peice of code and tried to use it but it doesnt work:

I load the first file like that: $list{$file}{$system}{$master_file_name}{$symbol}=$price;

and the second: $map{$file} = $charge;

and I join them: %combined = (%map, %list);

foreach my $system (keys(%combined))
{
my $n=0;
my $i=0;
      my $workbook = Spreadsheet::WriteExcel->new("system.xls");
my $worksheet   = $workbook->add_worksheet("summary_unmapped_master_file");
map{$worksheet->write($n, $i++,$_)}   ("list", "charge", "System", "MAster_file", "symbol", "price");
$n++;$i=0;
foreach my $value (sort{$combined{$system}{$b} <=> $combined{$system}{$a}} keys %{$combined{$system}})
{   
    map{$worksheet->write($n, $i++,$_)} ($value,$list{$system}{$value});
    $n++;$i=0;
}

}

I typically encourage posters to show some work. Its a sign of good faith that you have tried and something isn't working, rather than asking us to do your work for you. Thus I won't give an example. That said, I want to point you to Tie::Array::CSV . It can make this a much simpler task.

  • Open the file containing the prices
  • Read the prices file a line at a time and put the data into a hash keyed on the Key.
  • Open the other file
  • Open an output file
  • For each line in the other file
    • Look up the matching price in the prices hash
    • Append the price to the end of the existing record
    • Write the new record to the output file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM