Scan file for Floating point numbers with regex


/ Published in: Perl
Save to your folder(s)

Scans a file for a series of floating point numbers separated by spaces.


Copy this code and paste it in your HTML
  1. #!/usr/bin/perl
  2. # Usage in command line: perl <app> <file-to-be-converted> <width> <height>
  3. # e.g. <app> myGeo.geo 30 30
  4. # Parse .geo file and reformat as REFRACT-style height data file
  5.  
  6. my $origfile = $ARGV[0];
  7. my $sizeX = $ARGV[1];
  8. my $sizeY = $ARGV[2];
  9.  
  10. my $outfile = "refract_" . $origfile;
  11. my %hTmp;
  12.  
  13. open (IN, "<$origfile") or die "Couldn't open input file: $!";
  14. #open (OUT, ">$outfile") or die "Couldn't open output file: $!";
  15.  
  16. my $numPoints = 0;
  17. my $rowPoints = 0;
  18. my $dataOut = "";
  19.  
  20. while (my $sLine = <IN>) {
  21. #print "line\n";
  22. #if ($sLine =~ m/^([-+]?([0-9]*\.)?[0-9]+) ([-+]?([0-9]*\.)?[0-9]+) ([-+]?([0-9]*\.)?[0-9]+) [-+]?([0-9]*\.)?[0-9]+/) {
  23. if ($sLine =~ m/^([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+)\s+$/ ) {
  24. my $x = $1;
  25. my $y = $2;
  26. my $z = $3;
  27. my $myString = sprintf("%.4f", $y);
  28. $dataOut .= "$myString ";
  29. $rowPoints++;
  30. if ($rowPoints >= $sizeX) {
  31. $dataOut .= "\n";
  32. $rowPoints = 0;
  33. }
  34. $numPoints++;
  35. }
  36. }
  37. #close OUT;
  38. close IN;
  39. #print "Num points: $numPoints \n";
  40. print $dataOut;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.