I would like to add a feature in below code to check if both fruit and info input provided by user in cmd exist in the file. Meanwhile to fullfill 3 requirements below, first and second are completed with code below.
- If the fruit provided in cmd line not exist in file, then add it in with the info provided.
- If the fruit provided in cmd already exist in file, then add in info provided into it. Info 1 is mapping fruit1
- If both fruit and info provided in cmd already exist in file, skip it
cmd: <script> -fruit apple,orange,jackfruit -info y,c,a
File example:
apple
x
y
orange
a
b
Expected output (Since apple and y already in the file, skip it):
apple
x
y
orange
a
b
c
jackfruit
a
Code:
use strict;
use warnings;
use Tie::File;
my $help=0;
my $info;
my $fruit;
use Getopt::Long;
if (! GetOptions(
"fruit=s" => \$fruit,
"info=s" => \$info,
)){
print "\nEntered Arguments are not enough!\nPlease Use Switch '-help' or '-h' For More Information.\n";
exit;
}
my $split_info;
my $split_fruit;
my @split_info = split(',', $info);
my @split_fruit = split(',', $fruit);
my %new_data;
@new_data{@split_fruit}=@split_info;
tie my @file, 'Tie::File', "/nfs/site/disks/ipg_da_00003/ip7nm/sungyuan/script/regression_indicator/testing/2022.12.SP1/config.txt" or die $!;
for (0 .. $#file) {
next if /^\s/;
if (exists $new_data{$file[$_]}) {
splice @file, $_ + 1, 0, "\t$new_data{$file[$_]}\n";
# Delete our current key/value pair from the hash
delete $new_data{$file[$_]};
}
}
# For each key left in the hash...
for (keys %new_data) {
# Push two new lines into our tied file array
# (This adds new lines to the end of the file)
push @file, "$_\n", "\t$new_data{$_}\n";
}
It is not completely clear if the info values should be unique or not. Anyway I think this problem is more easily solved using a json file than using a custom file format. Here is an example using JSON input file format:
config.json
Then using this Perl script to read and modify the JSON input file:
If you prefer the original file format, you could try this instead: