Blurman
Blurman

Reputation: 609

Perl parsing file content

I am trying to parse text file content consists of 3 categories and access it in the main code. I got to know that hash maybe a good way but since no columns in the input file is unique (Name could be repeatedly or different), I doubt is there other way to do it. Appreciate any reply.

#!/usr/bin/perl

use strict; 
use warnings;

my $file = "/path/to/text.txt";
my %info = parseCfg($file);
#get first line data in text file (Eric cat xxx)
#get second line data in text file (Michelle dog yyy)
#so on

}

sub parseCfg {
    my $file = shift;
    my %data;
    return if !(-e $file);
    open(my $fh, "<", $file) or die "Can't open < $file: $!";
    my $msg = "-I-: Reading from config file: $file\n";
    while (<$fh>) {
        if (($_=~/^#/)||($_=~/^\s+$/)) {next;}
        my @fields = split(" ", $_);
        my ($name, $son, $address) = @fields;
        #return something
    }
    close $fh;
}

Input file format:(basically 3 columns)

#Name pet address    
Eric cat xxx
Michelle dog yyy
Ben horse zzz
Eric cat aaa

Upvotes: 1

Views: 109

Answers (1)

Polar Bear
Polar Bear

Reputation: 6798

The question isn't clear how the data will be used in the code.

Following code sample demonstrates how the data can be read and stored in anonymous hash referenced by $href. Then $href stored in anonymous array referenced in $aref which returned by parse_cnf() subroutine.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $fname = 'pet_data.txt';
my $data  = parse_cnf($fname);

say Dumper($data);

printf "Name: %-12s Pet: %-10s Address: %s\n", $_->@{qw/name pet address/} for $data->@*;

exit 0;

sub parse_cnf {
    my $fname = shift;  
    my $aref;
    
    open my $fh, '<', $fname
        or die "Couldn't open $fname";
        
    while( <$fh> ) {
        next if /(^\s*$|^#)/;
        my $href->@{qw/name pet address/} = split;
        push $aref->@*, $href;
    }
    
    close $fh;
    
    return $aref;
}

Output

$VAR1 = [
          {
            'address' => 'xxx',
            'pet' => 'cat',
            'name' => 'Eric'
          },
          {
            'pet' => 'dog',
            'name' => 'Michelle',
            'address' => 'yyy'
          },
          {
            'name' => 'Ben',
            'pet' => 'horse',
            'address' => 'zzz'
          },
          {
            'address' => 'aaa',
            'pet' => 'cat',
            'name' => 'Eric'
          }
        ];

Name: Eric         Pet: cat        Address: xxx
Name: Michelle     Pet: dog        Address: yyy
Name: Ben          Pet: horse      Address: zzz
Name: Eric         Pet: cat        Address: aaa

Upvotes: 3

Related Questions