0

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

3
  • simple state machine: read a line, figure out what it is, store it into the appopriate place. lather, rinse, repeat.
    – Marc B
    Feb 1, 2013 at 15:26
  • 7
    You don't want to do that. Use a hash instead.
    – melpomene
    Feb 1, 2013 at 15:27
  • Any examples would be great... I've been at it 6 hours, copy n pasting code all day to no avail... :)
    – shewang
    Feb 1, 2013 at 15:29

3 Answers 3

6

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.

1
  • The article "why it's stupid ...", which you linked is difficult to read and comprehend because it's written with teenager's angst and style, mostly filled with emotional judgement unrelated to and unnecessary to the question at hand. Difficult to piece together a comprehensive info set. Perhaps you could summarize it in your answer. Apr 28, 2023 at 3:27
3

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...
4
  • uptownnickbrown, thanks for the example, but this throws an error: Possible unintended interpolation of @NX_iPaaS in string at iPaaS2.pl line 11. syntax error at iPaaS2.pl line 9, near "<IN> {" Global symbol "@NX_iPaaS" requires explicit package name at iPaaS2.pl line 11. syntax error at iPaaS2.pl line 15, near "}" Execution of iPaaS2.pl aborted due to compilation errors.
    – shewang
    Feb 1, 2013 at 15:50
  • Sorry, I just tossed that up in SO without testing. As someone just edited, the @ needed to be escaped in the regex in line 11, like so: \@. Feb 1, 2013 at 15:52
  • Ah there was also a missing closing Parentheses at line 6 while (<$IN>) {
    – shewang
    Feb 1, 2013 at 15:59
  • Happy to help. You should really read the piece choroba linked to - good explanation of why you should attack this problem with a hash. Feb 1, 2013 at 16:03
-1
#!/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.

5
  • 2
    Don't use -w; missing use warnings; don't use bareword filehandles; don't use 2-arg open; check open's return value for errors; don't use foreach (<...>); avoid < >; $_=~ is redundant; \S+ may match = (i.e. your regex is probably wrong); don't use printf without a good reason.
    – melpomene
    Feb 1, 2013 at 15:50
  • Why not -w ? and printf ? Why is $_=~ redundant ?
    – Jean
    Feb 1, 2013 at 15:57
  • @Jean When you use warnings, you are able to selectively disable certain warning categories, e.g. no warnings 'redefine'. Using this instead of the -w switch is considered a best practice. Perl strings can interpolate variables; print "$_=$hash{$_}\n" is equivalent, and has less indirection. Use printf when you need advanced formatting (cutting strings at certain length, alignment, rounding, hex…). If a regex isn't bound via =~, it matches the topic variable $_ by default. for(<>) reads all lines at once; ` while(<>)` one line at a time. You meant the regex /^\@([^=]+)=(.*)$/
    – amon
    Feb 1, 2013 at 16:12
  • Thanks..Could you please give an example where my regex would fail ?
    – Jean
    Feb 1, 2013 at 16:17
  • @Jean The problem is values that may contain =. E.g. with [email protected] your regex would treat email=hello as the field name and [email protected] as the value. This is usually not what users expect.
    – melpomene
    Feb 1, 2013 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.