Dynamically Change the Key Value based on Delimiter
10:29 02 Jun 2020

I'm reading from a CSV file and populating a hash based on key-value Pairs. The First Column of the record is the key, and the rest of the record is the value. However, for some file, I need to make first 2 columns as key and the rest of the record is value. I have written it as below based on if loop by checking the number of Key Columns, but I wanted to know if there is any better way to do this.

use strict;
use warnings;

open my $fh, '<:encoding(utf8)', 'Sample.csv'
      or die "Couldn't open Sample.csv";
my %hash;     
my $KeyCols=2;
    while (<$fh>) {
        chomp;
        if ($KeyCols==1) {
            next unless /^(.*?),(.*)$/;
            $hash{$1} = $2;
        }
        elsif ($KeyCols==2) {
            next unless /^(.*?),(.*?),(.*)$/;
            $hash{$1.$2} = $3;
        }
    }
regex perl strawberry-perl