use strict; use warnings; # Given an ini file, return a string containing section contents. # (Note that ini file comment lines start with a ;) sub get_section { my $fcontents = shift; # in: ini file contents string my $section = shift; # in: section name to get # Note that the regex below will find multiple sections; # it's terminated by the start of a new section or end of file. my $s = join( "", $fcontents =~ /^[ \t]*\[$section\](.*?)(?:\Z|^[ \t]*\[)/msg ); $s =~ s/^[ \t]+//mg; # remove leading whitespace from each line $s =~ s/[ \t]+$//mg; # remove trailing whitespace from each line $s =~ s/^\s+//; # remove leading whitespace $s =~ s/\s+$//; # remove trailing whitespace # Remove up to three trailing comment lines $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s; return $s; } my $inifile_contents = <<'BUK_LIKES_SUNDIALS'; [MySection] ; This is a comment line for MySection fld1 = 'value of field 1' fld2 = 42 ; This is the heading for AnotherSection [AnotherSection] ; another comment asfld=69 BUK_LIKES_SUNDIALS my $section1 = get_section( $inifile_contents, 'MySection' ); print "This is the contents of MySection -------\n$section1\n"; my $section2 = get_section( $inifile_contents, 'AnotherSection' ); print "This is the contents of AnotherSection -------\n$section2\n"; #### This is the contents of MySection ------- ; This is a comment line for MySection fld1 = 'value of field 1' fld2 = 42 This is the contents of AnotherSection ------- ; another comment asfld=69 #### # Remove up to three trailing comment lines $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s; $s =~ s/^;.*\Z//m; chomp $s;