-1

I have to read & modify certain data from .lib file. I could extract the line in which the data is present, but I could not extract the number associated with it.

open my $fh, "<" ,".....lib" or die "$!";

while(my $line = <$fh>) {
      if ($line =~ m/xyz0/) {
         print $line;
      }
} 

The code outputs the line:

+xyz0 = 0.005 hg = 0.9 rvfd = 75

I want to extract the value beside xyz0 from it. How do I do it ?

clearlight
  • 12,255
  • 11
  • 57
  • 75
rahdirs
  • 13
  • 1
  • 6

1 Answers1

4
if ($line =~ m/xyz0 = (\S+)/){
    print $1;
}
ysth
  • 96,171
  • 6
  • 121
  • 214
  • 2
    Or if you want to avoid global vars: `if ( my ($xyz0) = $line =~ m/xyz0 = (\S+)/) { print $xyz0, "\n"; }` – ikegami Jan 30 '17 at 02:40
  • @rahdirs And if you are uncertain about spaces around `=` make it `/xyz0\s*=\s*(\S+)/` – zdim Jan 30 '17 at 02:58
  • How can I change the extracted value to some new number ? like 0.9 ? – rahdirs Jan 30 '17 at 03:15
  • @rahdirs one way would be with the [substitution operator](http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators) – Matt Jacob Jan 30 '17 at 04:00
  • @zdim,@ysth,@ikegami: `while(my $line = <$fh>){ if( my ($xyz0) = $line =~m/xyz0 = (\S+)/){ print $xyz0,"\n"; # this prints 0.005 $new_value = 0.9; $xyz0 =~ s/$xyz0/$new_value/; # How do I enter this value to file ?}}`. – rahdirs Jan 30 '17 at 05:54
  • @rahdirs In principle you need to rewrite the whole file. Search SO for that, there already are many posts. – zdim Jan 30 '17 at 06:05
  • @zdim,@ysth,@ikegami: Why do I have to rewrite the whole file ? I only need to increment the value by 15% each time – rahdirs Jan 30 '17 at 11:37
  • that's just how files work. unless you are updating a specific number of bytes in the file, if you want to change something you need to rewrite the whole remainder of the file. – ysth Jan 30 '17 at 14:55
  • in any case, this is a very separate question, so ask it as one – ysth Jan 30 '17 at 14:56