I have an SQL file which will give me an output like below:
10|1
10|2
10|3
11|2
11|4
.
.
.
I am using this in a Perl script like below:
my @tmp_cycledef = `sqlplus -s $connstr \@DLCycleState.sql`;
after this above statement, since @tmp_cycledef has all the output of the SQL query,
I want to show the output as:
10 1,2,3
11 2,4
How could I do this using Perl?
EDIT:
I am using the following code:
foreach my $row (@tmp_cycledef)
{
chomp $row;
my ($cycle_code,$cycle_month)= split /\s*\|\s*/, $row;
print "$cycle_code, $cycle_month\n";
$hash{$cycle_code}{$cycle_month}=1
}
foreach my $num ( sort keys %hash )
{
my $h = $hash{$num};
print join(',',sort keys %$h),"\n";
}
the fist print statement prints:
2, 1
2, 10
2, 11
2, 12
3, 1
3, 10
3, 11
but the out is always
1,10,11,12
1,10,11,12
1,10,11,12
1,10,11,12
1,10,11,12
1,10,11,12
1,10,11,12
Well, this one is actually how you might do it in perl:
Perl allows for variables to be created as they are used,
$feldman = some_function()means that you now have the variable$feldmanin your local namespace. But the bad part about this is that you can type$fldmanand take a long time finding out why what you thought was$feldmanhas no value. Turning on strictures means that your code fails to compile if it encounters an undeclared variable. You declare a variable with amyorourstatement (or in older Perl code ause varsstatement.Turning on
warningsjust warns you when you’re not getting values you expect. Often warnings tends to be too touchy, but they are generally a good thing to develop code with.Here, I’ve declared a hash variable that I creatively called
%hash. The sigil (pronounced “sijil”) “%” tells that it is a map of name-value pairs. Thismystatement declared the variable and makes it legal for the compiler. The compiler will warn me about any use of%hsh.The next item is a
foreachloop (which can be abbreviated “for”). The loop will process the list of lines in@tmp_cycledefassigning each one in turn to$row. ( my$row).chompthe line first, removing the end-of-line character for that platform.splitthe line on the ‘|’ character, creating a list of strings that had been separated by a pipe.push @{$hash{$key}}, $val, but I typically want to collapse duplicates (not that there were any duplicates in your sample.)Here:
Once we have the data in the structure, we need to iterate both level of hash
keys. You wanted to separate the “top level” numbers by lines, but you wanted the second numbers concatenated on the same line. So we print a line for each of the first numbers andjointhe list of strings stored for each number on the same line, delimited by commas. We also sort the list:{ $a <=> $b }just takes to keys and numerically compares them. So you get a numeric order.As I said in the comments,
sort, by default, sorts in character order so you can just saysort keys %hash.To help you out, you really need to read some of these:
my,foreach,chomp,split,keys,sortandjoin