shewang
shewang

Reputation: 3

Perl reading a file and storing each line as variable/value

I'm pretty new to perl, but so far got to do pretty much everything I needed to, until now.

I have a file formatted like so:

#IPAAS

@NX_iPaaS_AuthKey=dGstaG9zaGlub0BqcCasdpasdHN1LmNvbTppUGFhUzAw
@NX_iPaaS_href=live/661134565/process/75231

I'd like to read each line that begins with @NX_iPaaS into a similar named variable, e.g. @NX_iPaaS_AuthKey would create a new variable called $NX_IPAAS_AUTHKEY and hold the value, NX_iPaaS_href would result in a new variable called $NX_IPAAS_HREF with a value and so on?

--Update--

Hey guys, I need a slight tweak required to the above solution...

So I've just discovered that the file I'm reading in will have 'sections', e.g.

----- SECTION=cr 
NX_NTF_PERSISTENT_ID=cr:400017 
NX_NTF_REF_NUM=45 
----- SECTION=cnt 
NX_NTF_PERSISTENT_ID=cnt:F9F342055699954C93DE36923835A182 

You can see that one of the variables appears in both sections, which (because I don't have 'next unless defined') results in the previous value being overwritten. Is there a way to prefix the NX_NTF_ variable names with the value provided on the 'section=' line at the top of each section?

Thanks

Upvotes: 0

Views: 9928

Answers (3)

uptownnickbrown
uptownnickbrown

Reputation: 997

What you want to use is a hash. Something like:

use strict;
use warnings;

my $input = "yourfilename.txt";
open(my $IN, "<", $input) or die "$0: Can't open input file $input: $!\n";

my %NX_iPaaS_vars;

while (<$IN>) {
    chomp;
    if ($_ =~ /^\@NX_iPaaS/) {
        my ($key, $value) = split(/=/, $_);
        $NX_iPaaS_vars{$key} = $value;
    }
}

To use a variable later on, use $NX_iPaaS_vars{"name of variable you want"}, for example:

my $href_path = $NX_iPaaS_vars{'@NX_iPaaS_href'};
# Do something with $href_path here...

Upvotes: 3

choroba
choroba

Reputation: 241868

The good practice is to use hashes.

my %hash;
while (<>) {
    chomp;
    my ($key, $value) = split /=/;
    next unless defined $value;
    $hash{$key} = $value;
}

See Why it's stupid to "use a variable as a variable name" on why it is not a good idea to use variable variable names.

Upvotes: 6

Jean
Jean

Reputation: 22695

#!/usr/bin/perl -w
use strict;

open(FILE,"test.txt");

my %hash;

foreach (<FILE>)
{
       if($_=~/@(\S+)=(\S+)/)
       {
               $hash{$1}=$2;
       }

}
close(FILE);

# Test Code

foreach (keys %hash)
{
       printf("%s=%s\n",$_,$hash{$_});
}

This solution works well if variable names are unique.

Upvotes: -1

Related Questions