Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for readini.pl

(view source code of readini.pl as plain text)

  1. #! perl
  2.  
  3. # Store help text in variable
  4. $syntax = "\nReadINI.pl,  Version 1.10\n";
  5. $syntax = $syntax."Read a value from the specified INI file\n\n";
  6. $syntax = $syntax."Usage:  READINI.PL  \"ini_file\"  \"section\"  \"key\"\n\n";
  7. $syntax = $syntax."Where:           \"ini_file\" is the file name of the INI file to be read\n";
  8. $syntax = $syntax."                 \"section\"  is the section name, without the brackets\n";
  9. $syntax = $syntax."                 \"key\"      is the key whose value must be read\n\n";
  10. $syntax = $syntax."Example: if MYPROG.INI looks like this:\n";
  11. $syntax = $syntax."[Section 1]\n";
  12. $syntax = $syntax."Key1=Value 1\n";
  13. $syntax = $syntax."Key2=Value 2\n";
  14. $syntax = $syntax."[Section 2]\n";
  15. $syntax = $syntax."Key2=Value 3\n";
  16. $syntax = $syntax."[Section 3]\n";
  17. $syntax = $syntax."Key2=Value 4\n";
  18. $syntax = $syntax."Then the command:  READINI.PL  \"MYPROG.INI\"  \"section 2\"  \"key2\"\n";
  19. $syntax = $syntax."should return:     Value 3\n\n";
  20. $syntax = $syntax."Written by Rob van der Woude\n";
  21. $syntax = $syntax."http://www.robvanderwoude.com\n";
  22.  
  23. # Switch to slurp mode
  24. undef $/;
  25.  
  26. # Check command line arguments and open INI file
  27. if ( @ARGV[2] ) {
  28. 	$ini     = @ARGV[0];
  29. 	open( STDIN, "< $ini" ) || die "Cannot open file $ini\n$!\n\n$syntax";
  30. 	$section = @ARGV[1];
  31. 	$key     = @ARGV[2];
  32. } else {
  33. 	die "$syntax";
  34. }
  35.  
  36. # Changed ([^\n]*\n)* into ([^\[][^\n]*\n)*? after a bug report by Boby Dumoulin
  37. while ( <STDIN> ) {
  38. 	if ( $_ =~ m/^\[$section\]\s*\n([^\[][^\n]*\n)*?"?$key"?\s*=\s*"?([^\n]+)"?\s*(\n|$)/im ) {
  39. 		print "\n\"$ini\"\n";
  40. 		print "[$section]\n";
  41. 		print "$key=$2\n";
  42. 	}
  43. }
  44.  
  45. # Close INI file
  46. close STDIN;
  47.  

page last modified: 2024-04-16; loaded in 0.0069 seconds