Home > Software design >  How to print data by avoiding last comma
How to print data by avoiding last comma

Time:09-07

I have a data in my hash and trying to print them in the console.

Below is my script:

#!/usr/bin/perl

use strict; use warnings;
use Data::Dumper;

my %hash = (
  '2022-08-04' => {
      'Method 1' => {
            'Count' => 50,
            'Size' => '10 MB'
      },
      'Method 2' => {
            'Count' => 40,
            'Size' => '5 MB'
      }
  },
  '2022-08-05' => {
      'Method 1' => {
            'Count' => 30,
            'Size' => '3 MB'
      },
      'Method 2' => {
            'Size' => '50 MB',
            'Count' => '100'
      }
  }
);

my @headers = ("Method 1", "Method 2");

my @headers_data;
push (@headers_data, "Date");
foreach (@headers) {
  push(@headers_data, $_." Size", $_." Count");
}
print join(",", @headers_data);
print "\n";

for my $date ( sort keys( %hash ) ) {
  my $by_method = $hash{$date};
  print "$date,";

  for my $method ( @headers ) {
    my $rec = $by_method->{$method};
    $rec->{Size} = $rec->{Size} ? $rec->{Size} : "NA";
    $rec->{Count} = $rec->{Count} ? $rec->{Count} : "NA";    
    print "$rec->{Size},$rec->{Count},";
  }
  print "\n";
}

Here when I print in line print "$rec->{Size},$rec->{Count},";, this gives , at the end of the result which looks odd to me.

Example:

Date,Method 1 Size,Method 1 Count,Method 2 Size,Method 2 Count
2022-08-04,10 MB,50,5 MB,40,
2022-08-05,3 MB,30,50 MB,100,

You can see there is a comma(,) in line 2 and 3 of the result.

When I tried below logic (which is similar of printing @headers_data) I got stuck how to proceed with printing @data in the console, since it contains two days data together.

...
my @data;
for my $date ( sort keys( %hash ) ) {
  my $by_method = $hash{$date};
  push (@data, $date);

  for my $method ( @headers ) {
    my $rec = $by_method->{$method};
    $rec->{Size} = $rec->{Size} ? $rec->{Size} : "NA";
    $rec->{Count} = $rec->{Count} ? $rec->{Count} : "NA";    
    push (@data, $rec->{Size}, $rec->{Count});
  }
}

Could someone please help me to print results like below:

Date,Method 1 Size,Method 1 Count,Method 2 Size,Method 2 Count
2022-08-04,10 MB,50,5 MB,40
2022-08-05,3 MB,30,50 MB,100

CodePudding user response:

Modifying your first script:

...
for my $date ( sort keys( %hash ) ) {
  my $by_method = $hash{$date};
  my @line_data;
  push @line_data, $date;

  for my $method ( @headers ) {
    my $rec = $by_method->{$method};
    $rec->{Size} = $rec->{Size} ? $rec->{Size} : "NA";
    $rec->{Count} = $rec->{Count} ? $rec->{Count} : "NA";    
    push(@line_data, $rec->{Size}, $rec->{Count});
  }
  print join(",", @line_data), "\n";
}
  • Related