0
votes

Hi i am new to Perl programming. I am trying to read a .csv file which has 2 fields separated by comma.

I want to put all the data of a file into a hash in the form of key and its value.

The input file I have is

Data

2.8, gitu

2.5,  Has


2.7  Hwait

3.1-weiity

4.2,  city

2.7:query

4.9,  city

16.2,  play

6.2,  game

7,,,8 Jami

4.0,  city

This line of code does not print all the valid data present in the input file. Valid data is in the form of a line start with a number have a comma in between and then a name. Else invalid entries should be ignored. It skips few valid entries to display when I print %hashforHighMagnitude; Please tell me where I am missing ? How can I get all the valid entries present %hashforHighMagnitude;

I am trying to do this

open ( OF, "$inputFile") or die "Cant open input file: $!\n";
while ( $Line =<OF>) {

    if($Line =~ /^\d+\.+\d*\s*,\s*\w+$/g)              
    {
        ( my $magnitude, my $place ) = split(/,/,$Line);

        $hashforHighMagnitude{$place} = $magnitude;
        $hash{$place}++;
    }
    else
    {
        next;
    }
}

print %hashforHighMagnitude;

close(OF);

output should be

2.8, gitu

2.5,  Has

4.2,  city

4.9,  city

16.2,  play

6.2,  game

4.0,  city
2

2 Answers

6
votes

Due to the presence of edge cases while parsing CSVs, a specialised module should be used. Some modules worth considering are:

Program

#!/usr/bin/env perl

use strict;
use warnings;

use Text::CSV;

my $csv = Text::CSV->new( { 'allow_whitespace' => 1 } )
  or die Text::CSV->error_diag;

while ( my $row = $csv->getline( \*DATA ) ) {
    if ( @$row == 2 ) {
        print join( ', ', @$row ), "\n";
    }
}

__DATA__
2.8, gitu
2.5,  Has
2.7  Hwait
3.1-weiity
4.2,  city
2.7:query
4.9,  city
16.2,  play
6.2,  game
7,,,8 Jami
4.0,  city

Output

2.8, gitu
2.5, Has
4.2, city
4.9, city
16.2, play
6.2, game
4.0, city
1
votes

Well i was able to find my mistake . what i was doing wrong was that i was not able to add all the entries properly. i was needed to replace my line of code from

$hashforHighMagnitude{$place} = $magnitude; 

to

$hashforHighMagnitude{$place} .=exists $hashforHighMagnitude{$place} ? "  $magnitude" :$magnitude;

thats it. now i was able to get the desired output ... thanks everyone for taking a look at my query .....