Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex Result into Hash (and file) 2

Status
Not open for further replies.

stevio

Vendor
Jul 24, 2002
78
AU
I run a command which has the following results from STDOUT:

Serial=102345
Name=Server1
Type=Windows
....

Serial=345069
Name=Server2
Type=Linux
...

etc

How do I place each combo of serial and type into a hash for easy reference

Code:
my %hash;
my @cmd = `command`;
    foreach $line(@cmd) {
       if ($line1 =~ /^Server=(\d{6})) {
            if ($line2=~ /^Type=(\w+)) {
              #enter $line1 and $line2 values into hash 
              # I know this is wrong
              $hash($1)= $2;
              #write results out to file
           }
       }
    }

The idea is to get a hash like so

102345 => Windows
345069 =>Linux
etc

File should look like:

102345=Windows
345069=Linux
etc
 
Code:
my%hash;
my@cmd=`command`;
my$temp;
for$line(@cmd){
  if($line=~/^Serial=(\d{6})/){
    $temp=$1;
  }elsif($line=~/^Type=(\w+)/){
    $hash($temp)=$1;
  }
}
This will only work if a legal Serial line will always be followed by the corresponding Type line. Some error checking would be in order, as the whole sequence would be messed in case of an error (e.g. a Serial line with only 5 digits)

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Code:
       [blue]if ($line1 =~ /^Server=(\d{6})) {[/blue]
            [fuchsia]if ($line2=~ /^Type=(\w+)) {[/fuchsia]
              #enter $line1 and $line2 values into hash
              # I know this is wrong
              $hash($1)= $2;
              #write results out to file
           }
       }

In the blue line, $1 is set to whatever matched (\d{6}), and in the magenta line, $1 is set to whatever matched (\w+). So there is no $2 here, just $1 being set twice.

So you'd need to temporarily copy $1 off to a different variable before you run the next regexp, cuz each regexps clobber $1-$n when run.

Code:
       if ($line1 =~ /^Server=(\d{6})) {
            my $temp = $1;
            if ($line2=~ /^Type=(\w+)) {
              #enter $line1 and $line2 values into hash
              # I know this is wrong
              $hash{$temp}= $1;
              #write results out to file
           }
       }

Also, hashes use curly braces {}, not parenthesis ().

Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top