Search code examples
perlprintingno-duplicates

Find all strings in a file that are the same and print the value after in perl


Good Day guys.

I am trying to print from an excel file to a ini file, I have the excel and ini writing sorted, but my issue lies with getting the values without duplicating.

The excel file will contain something like this

    House        |     133_Anderson_str
    Shop         |     12_Smith_Str
    Wheelshop    |     832_Smith_Str
    House        |     21_smith_Str
    Shop         |     1191_dandelion_rd

If I do a foreach and print it to the ini file I will get a result like this

    [House]
    adress=133_Anderson_str

    [Shop]
    adress=12_Smith_Str

    [Wheelshop]
    address=832_Smith_Str

    [House]
    adress=21_smith_Str

    [Shop]
    address=1191_dandelion_rd

This cannot work because if I run the gui that will search for all adresses under house, it will only reference the first one and then end at the new line. I want to print each duplicate value once and then the next value after it should be printed like this

    [House]
    adress=133_Anderson_str, 21_smith_Str

    [Shop]
    adress=12_Smith_Str, 1191_dandelion_rd


    [Wheelshop]
    address=832_Smith_Str

I have tried a has table, but I cannot get to print in the correct order and make sure that each value gets printed to the correct key and without duplicating the key.

I am using Config::Inifiles to print and read the ini and SpreadSheet::Read to get the data from the spreadsheet.

Hope someone can show me the light!

Thanks a mill.


Solution

  • This should be @input array with 5 lines/elements,

    House        |     133_Anderson_str
    Shop         |     12_Smith_Str
    Wheelshop    |     832_Smith_Str
    House        |     21_smith_Str
    Shop         |     1191_dandelion_rd
    

    First, %hash is used to group elements of @input into hash of arrays structure,

    my %hash;
    for my $line (@input) {
    
      # $k = "House"; $v ="133_Anderson_str", etc.
      my ($k, $v) = split / [\s\|]+ /x, $line;
    
      my $arr = $hash{$k} ||= [];
      push @$arr, $v;
    }
    

    Now when grouping is done, proceed with output,

    for my $k (sort keys %hash) {
    
      my $arr = $hash{$k};
      my $vals = join ", ", @$arr;
    
      print "[$k]\n", "address=$vals\n\n";
    }