Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Perl parsing file

by Eily (Prior)
on May 30, 2014 at 16:05 UTC ( #1088022=note: print w/replies, xml ) Need Help??

in reply to Perl parsing file

It's easier to see what you were trying to do when you provide codes that work. Yours won't even compile (you forgot the parenthesis in the first if, and I suppose you forgot the second if).

A hash key is unique, so if you want something to be unique, put it in a hash key. In your case, since you don't want to erase the previous value each time you find a new one, you have to check if a key already exists. This can be done in perl with the keyword exists: $hashref->{$sid} = $alias unless exists $hashref->{$sid};

If you set the special variable $/ to the empty string, perl will read your input file paragraph by paragraph instead of line by line. This means from "DB1.UK" until the ")" just before the next alias. Maybe you already used that, but since the code you have posted can't even compile, I can't tell.

So with all this (I didn't want to give you a fully fonctionnal solution, but there's not much left to change):

use Data::Dumper; my %result; # Be careful here, I used a hash, not a hashref { local $/ = ""; # make sure the change to $/'s value doesn't leek to +the rest of the program while(<DATA>) # Read the lines at the end like a input file { if (/^([a-z][\w.]+)/i) # a line starting by a letter, followed by +letters, numbers or a dot { my $alias = $1; my $sid = whoops!; # here some code to find the value of $sid $result{$sid} = $alias unless exists $result{$sid}; # keep the +alias unless the sid is already known } } print Dumper \%result; # show result __DATA__ DB1.UK, DB2.UK = ( (ADDRESS = (PROTOCAL = TCP)) (CONNECT_DATA = (SID = db1)) ) DB1.EU, DB2.CH = ( (ADDRESS = (PROTOCAL = TCP)) (CONNECT_DATA = (SID = db1)) ) DB3.UK = ( (ADDRESS = (PROTOCAL = TCP)) (CONNECT_DATA = (SID = db3)) ) DB3.US = ( (ADDRESS = (PROTOCAL = TCP)) (CONNECT_DATA = (SID = db3)) ) DB5.UK.US, DB5.US = ( (ADDRESS = (PROTOCAL = TCP)) (CONNECT_DATA = (SID = db5)) )

When this works, look at values and reverse to see what you can do with that hash.

Replies are listed 'Best First'.
Re^2: Perl parsing file
by homer4all (Acolyte) on May 30, 2014 at 16:27 UTC
    Thank you very much Eily for looking into this and giving me your valuable time.. I will definitely look into this and check the link which you provided. Since I don't have fully functional code and also using tution school inbuilt packages to connect so didn't had much to post.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1088022]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2018-04-22 01:47 GMT
Find Nodes?
    Voting Booth?