/usr/share/perl5/Config/IniFiles.pm is in libconfig-inifiles-perl 2.68-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 | package Config::IniFiles;
use vars qw($VERSION);
$VERSION = '2.68';
require 5.004;
use strict;
use Carp;
use Symbol 'gensym','qualify_to_ref'; # For the 'any data type' hack
@Config::IniFiles::errors = ( );
# $Header: /home/shlomi/progs/perl/cpan/Config/IniFiles/config-inifiles-cvsbackup/config-inifiles/IniFiles.pm,v 2.41 2003-12-08 10:50:56 domq Exp $
=head1 NAME
Config::IniFiles - A module for reading .ini-style configuration files.
=head1 SYNOPSIS
use Config::IniFiles;
my $cfg = Config::IniFiles->new( -file => "/path/configfile.ini" );
print "The value is " . $cfg->val( 'Section', 'Parameter' ) . "."
if $cfg->val( 'Section', 'Parameter' );
=head1 DESCRIPTION
Config::IniFiles provides a way to have readable configuration files outside
your Perl script. Configurations can be imported (inherited, stacked,...),
sections can be grouped, and settings can be accessed from a tied hash.
=head1 FILE FORMAT
INI files consist of a number of sections, each preceded with the
section name in square brackets, followed by parameter names and
their values.
[a section]
Parameter=Value
[section 2]
AnotherParameter=Some value
Setting=Something else
Parameter=Different scope than the one in the first section
The first non-blank character of the line indicating a section must
be a left bracket and the last non-blank character of a line indicating
a section must be a right bracket. The characters making up the section
name can be any symbols at all. However section names must be unique.
Parameters are specified in each section as Name=Value. Any spaces
around the equals sign will be ignored, and the value extends to the
end of the line (including any whitespace at the end of the line.
Parameter names are localized to the namespace of the section, but must
be unique within a section.
Both the hash mark (#) and the semicolon (;) are comment characters.
by default (this can be changed by configuration). Lines that begin with
either of these characters will be ignored. Any amount of whitespace may
precede the comment character.
Multi-line or multi-valued parameters may also be defined ala UNIX
"here document" syntax:
Parameter=<<EOT
value/line 1
value/line 2
EOT
You may use any string you want in place of "EOT". Note that whatever
follows the "<<" and what appears at the end of the text MUST match
exactly, including any trailing whitespace.
Alternately, as a configuration option (default is off), continuation
lines can be allowed:
[Section]
Parameter=this parameter \
spreads across \
a few lines
=head1 USAGE -- Object Interface
Get a new Config::IniFiles object with the I<new> method:
$cfg = Config::IniFiles->new( -file => "/path/config_file.ini" );
$cfg = new Config::IniFiles -file => "/path/config_file.ini";
Optional named parameters may be specified after the configuration
file name. See the I<new> in the B<METHODS> section, below.
Values from the config file are fetched with the val method:
$value = $cfg->val('Section', 'Parameter');
If you want a multi-line/value field returned as an array, just
specify an array as the receiver:
@values = $cfg->val('Section', 'Parameter');
=head1 METHODS
=head2 new ( [-option=>value ...] )
Returns a new configuration object (or "undef" if the configuration
file has an error, in which case check the global C<@Config::IniFiles::errors>
array for reasons why). One Config::IniFiles object is required per configuration
file. The following named parameters are available:
=over 10
=item I<-file> filename
Specifies a file to load the parameters from. This 'file' may actually be
any of the following things:
1) the pathname of a file
$cfg = Config::IniFiles->new( -file => "/path/to/config_file.ini" );
2) a simple filehandle
$cfg = Config::IniFiles->new( -file => STDIN );
3) a filehandle glob
open( CONFIG, "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => *CONFIG );
4) a reference to a glob
open( CONFIG, "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => \*CONFIG );
5) an IO::File object
$io = IO::File->new( "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => $io );
or
open my $fh, '<', "/path/to/config_file.ini" or die $!;
$cfg = Config::IniFiles->new( -file => $fh );
6) A reference to a scalar (requires newer versions of IO::Scalar)
$ini_file_contents = <<EOT
[section name]
Parameter=A value
Setting=Another value
EOT
$cfg = Config::IniFiles->new( -file => \$ini_file_contents );
If this option is not specified, (i.e. you are creating a config file from scratch)
you must specify a target file using L<SetFileName> in order to save the parameters.
=item I<-default> section
Specifies a section to be used for default values. For example, in the
following configuration file, if you look up the "permissions" parameter
in the "joe" section, there is none.
[all]
permissions=Nothing
[jane]
name=Jane
permissions=Open files
[joe]
name=Joseph
If you create your Config::IniFiles object with a default section of "all" like this:
$cfg = Config::IniFiles->new( -file => "file.ini", -default => "all" );
Then requsting a value for a "permissions" in the [joe] section will
check for a value from [all] before returning undef.
$permissions = $cfg->val( "joe", "permissions"); // returns "Nothing"
=item I<-fallback> section
Specifies a section to be used for parameters outside a section. Default is none.
Without -fallback specified (which is the default), reading a configuration file
which has a parameter outside a section will fail. With this set to, say,
"GENERAL", this configuration:
wrong=wronger
[joe]
name=Joseph
will be assumed as:
[GENERAL]
wrong=wronger
[joe]
name=Joseph
Note that Config::IniFiles will also omit the fallback section header when
outputing such configuration.
=item I<-nocase> 0|1
Set -nocase => 1 to handle the config file in a case-insensitive
manner (case in values is preserved, however). By default, config
files are case-sensitive (i.e., a section named 'Test' is not the same
as a section named 'test'). Note that there is an added overhead for
turning off case sensitivity.
=item I<-import> object
This allows you to import or inherit existing setting from another
Config::IniFiles object. When importing settings from another object,
sections with the same name will be merged and parameters that are
defined in both the imported object and the I<-file> will take the
value of given in the I<-file>.
If a I<-default> section is also given on this call, and it does not
coincide with the default of the imported object, the new default
section will be used instead. If no I<-default> section is given,
then the default of the imported object will be used.
=item I<-allowcontinue> 0|1
Set -allowcontinue => 1 to enable continuation lines in the config file.
i.e. if a line ends with a backslash C<\>, then the following line is
appended to the parameter value, dropping the backslash and the newline
character(s).
Default behavior is to keep a trailing backslash C<\> as a parameter
value. Note that continuation cannot be mixed with the "here" value
syntax.
=item I<-allowempty> 0|1
If set to 1, then empty files are allowed at L</ReadConfig|ReadConfig()>
time. If set to 0 (the default), an empty configuration file is considered
an error.
=item I<-negativedeltas> 0|1
If set to 1 (the default if importing this object from another one),
parses and honors lines of the following form in the configuration
file:
; [somesection] is deleted
or
[inthissection]
; thisparameter is deleted
If set to 0 (the default if not importing), these comments are treated
like ordinary ones.
The L</WriteConfig|WriteConfig(-delta=>1)> form will output such
comments to indicate deleted sections or parameters. This way,
reloading a delta file using the same imported object produces the
same results in memory again. See L<IMPORT / DELTA FEATURES> for more
details.
=item I<-commentchar> 'char'
The default comment character is C<#>. You may change this by specifying
this option to another character. This can be any character except
alphanumeric characters, square brackets or the "equal" sign.
=item I<-allowedcommentchars> 'chars'
Allowed default comment characters are C<#> and C<;>. By specifying this
option you may change the range of characters that are used to denote a
comment line to include any set of characters
Note: that the character specified by B<-commentchar> (see above) is
I<always> part of the allowed comment characters.
Note 2: The given string is evaluated as a regular expression character
class, so '\' must be escaped if you wish to use it.
=item I<-reloadwarn> 0|1
Set -reloadwarn => 1 to enable a warning message (output to STDERR)
whenever the config file is reloaded. The reload message is of the
form:
PID <PID> reloading config file <file> at YYYY.MM.DD HH:MM:SS
Default behavior is to not warn (i.e. -reloadwarn => 0).
This is generally only useful when using Config::IniFiles in a server
or daemon application. The application is still responsible for determining
when the object is to be reloaded.
=item I<-nomultiline> 0|1
Set -nomultiline => 1 to output multi-valued parameter as:
param=value1
param=value2
instead of the default:
param=<<EOT
value1
value2
EOT
As the later might not be compatible with all applications.
=item I<-handle_trailing_comment> 0|1
Set -handle_trailing_comment => 1 to enable support of parameter trailing
comments.
For example, if we have a parameter line like this:
param1=value1;comment1
by default, handle_trailing_comment will be set to B<0>, and we will get
I<value1;comment1> as the value of I<param1>. If we have
-handle_trailing_comment set to B<1>, then we will get I<value1>
as the value for I<param1>, and I<comment1> as the trailing comment of
I<param1>.
Set and get methods for trailing comments are provided as
L</SetParameterTrailingComment> and L</GetParameterTrailingComment>.
=back
=cut
sub new {
my $class = shift;
my %parms = @_;
my $errs = 0;
my @groups = ( );
my $self = bless {
default => '',
fallback =>undef,
fallback_used => 0,
imported =>undef,
v =>{},
cf => undef,
firstload => 1,
nomultiline => 0,
handle_trailing_comment => 0,
}, $class;
if( ref($parms{-import}) && ($parms{-import}->isa('Config::IniFiles')) ) {
$self->{imported}=$parms{-import}; # ReadConfig will load the data
$self->{negativedeltas}=1;
} elsif( defined $parms{-import} ) {
carp "Invalid -import value \"$parms{-import}\" was ignored.";
} # end if
delete $parms{-import};
# Copy the original parameters so we
# can use them when we build new sections
%{$self->{startup_settings}} = %parms;
# Parse options
my($k, $v);
local $_;
$self->{nocase} = 0;
# Handle known parameters first in this order,
# because each() could return parameters in any order
if (defined ($v = delete $parms{'-file'})) {
# Should we be pedantic and check that the file exists?
# .. no, because now it could be a handle, IO:: object or something else
$self->{cf} = $v;
}
if (defined ($v = delete $parms{'-nocase'})) {
$self->{nocase} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-default'})) {
$self->{default} = $self->{nocase} ? lc($v) : $v;
}
if (defined ($v = delete $parms{'-fallback'})) {
$self->{fallback} = $self->{nocase} ? lc($v) : $v;
}
if (defined ($v = delete $parms{'-reloadwarn'})) {
$self->{reloadwarn} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-nomultiline'})) {
$self->{nomultiline} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-allowcontinue'})) {
$self->{allowcontinue} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-allowempty'})) {
$self->{allowempty} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-negativedeltas'})) {
$self->{negativedeltas} = $v ? 1 : 0;
}
if (defined ($v = delete $parms{'-commentchar'})) {
if(!defined $v || length($v) != 1) {
carp "Comment character must be unique.";
$errs++;
}
elsif($v =~ /[\[\]=\w]/) {
# must not be square bracket, equal sign or alphanumeric
carp "Illegal comment character.";
$errs++;
}
else {
$self->{comment_char} = $v;
}
}
if (defined ($v = delete $parms{'-allowedcommentchars'})) {
# must not be square bracket, equal sign or alphanumeric
if(!defined $v || $v =~ /[\[\]=\w]/) {
carp "Illegal value for -allowedcommentchars.";
$errs++;
}
else {
$self->{allowed_comment_char} = $v;
}
}
if (defined ($v = delete $parms{'-handle_trailing_comment'})) {
$self->{handle_trailing_comment} = $v ? 1 : 0;
}
$self->{comment_char} = '#' unless exists $self->{comment_char};
$self->{allowed_comment_char} = ';' unless exists $self->{allowed_comment_char};
# make sure that comment character is always allowed
$self->{allowed_comment_char} .= $self->{comment_char};
$self->{_comments_at_end_of_file} = [];
# Any other parameters are unkown
while (($k, $v) = each %parms) {
carp "Unknown named parameter $k=>$v";
$errs++;
}
return undef if $errs;
if ($self->ReadConfig) {
return $self;
} else {
return undef;
}
}
=head2 val ($section, $parameter [, $default] )
Returns the value of the specified parameter (C<$parameter>) in section
C<$section>, returns undef (or C<$default> if specified) if no section or
no parameter for the given section exists.
If you want a multi-line/value field returned as an array, just
specify an array as the receiver:
@values = $cfg->val('Section', 'Parameter');
A multi-line/value field that is returned in a scalar context will be
joined using $/ (input record separator, default is \n) if defined,
otherwise the values will be joined using \n.
=cut
sub val {
my ($self, $sect, $parm, $def) = @_;
# Always return undef on bad parameters
return if not defined $sect;
return if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
my $val = defined($self->{v}{$sect}{$parm}) ?
$self->{v}{$sect}{$parm} :
$self->{v}{$self->{default}}{$parm};
# If the value is undef, make it $def instead (which could just be undef)
$val = $def unless defined $val;
# Return the value in the desired context
if (wantarray) {
if (ref($val) eq "ARRAY") {
return @$val;
} elsif (defined($val)) {
return $val;
} else {
return;
}
} elsif (ref($val) eq "ARRAY") {
if (defined ($/)) {
return join "$/", @$val;
} else {
return join "\n", @$val;
}
} else {
return $val;
}
}
=head2 exists($section, $parameter)
True if and only if there exists a section C<$section>, with
a parameter C<$parameter> inside, not counting default values.
=cut
sub exists {
my ($self, $sect, $parm)=@_;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
return (exists $self->{v}{$sect}{$parm});
}
=head2 push ($section, $parameter, $value, [ $value2, ...])
Pushes new values at the end of existing value(s) of parameter
C<$parameter> in section C<$section>. See below for methods to write
the new configuration back out to a file.
You may not set a parameter that didn't exist in the original
configuration file. B<push> will return I<undef> if this is
attempted. See B<newval> below to do this. Otherwise, it returns 1.
=cut
sub push {
my ($self, $sect, $parm, @vals)=@_;
return undef if not defined $sect;
return undef if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
return undef if (! defined($self->{v}{$sect}{$parm}));
return 1 if (! @vals);
$self->_touch_parameter($sect, $parm);
$self->{EOT}{$sect}{$parm} = 'EOT' if
(!defined $self->{EOT}{$sect}{$parm});
$self->{v}{$sect}{$parm} = [$self->{v}{$sect}{$parm}] unless
(ref($self->{v}{$sect}{$parm}) eq "ARRAY");
CORE::push @{$self->{v}{$sect}{$parm}}, @vals;
return 1;
}
=head2 setval ($section, $parameter, $value, [ $value2, ... ])
Sets the value of parameter C<$parameter> in section C<$section> to
C<$value> (or to a set of values). See below for methods to write
the new configuration back out to a file.
You may not set a parameter that didn't exist in the original
configuration file. B<setval> will return I<undef> if this is
attempted. See B<newval> below to do this. Otherwise, it returns 1.
=cut
sub setval {
my $self = shift;
my $sect = shift;
my $parm = shift;
my @val = @_;
return undef if not defined $sect;
return undef if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
if (defined($self->{v}{$sect}{$parm})) {
$self->_touch_parameter($sect, $parm);
if (@val > 1) {
$self->{v}{$sect}{$parm} = \@val;
$self->{EOT}{$sect}{$parm} = 'EOT';
} else {
$self->{v}{$sect}{$parm} = shift @val;
}
return 1;
} else {
return undef;
}
}
=head2 newval($section, $parameter, $value [, $value2, ...])
Assignes a new value, C<$value> (or set of values) to the
parameter C<$parameter> in section C<$section> in the configuration
file.
=cut
sub newval {
my $self = shift;
my $sect = shift;
my $parm = shift;
my @val = @_;
return undef if not defined $sect;
return undef if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
$self->AddSection($sect);
CORE::push(@{$self->{parms}{$sect}}, $parm)
unless (grep {/^\Q$parm\E$/} @{$self->{parms}{$sect}} );
$self->_touch_parameter($sect, $parm);
if (@val > 1) {
$self->{v}{$sect}{$parm} = \@val;
$self->{EOT}{$sect}{$parm} = 'EOT' unless defined $self->{EOT}{$sect}{$parm};
} else {
$self->{v}{$sect}{$parm} = shift @val;
}
return 1
}
=head2 delval($section, $parameter)
Deletes the specified parameter from the configuration file
=cut
sub delval {
my $self = shift;
my $sect = shift;
my $parm = shift;
return undef if not defined $sect;
return undef if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
@{$self->{parms}{$sect}} = grep !/^\Q$parm\E$/, @{$self->{parms}{$sect}};
$self->_touch_parameter($sect, $parm);
delete $self->{v}{$sect}{$parm};
return 1
}
=head2 ReadConfig
Forces the configuration file to be re-read. Returns undef if the
file can not be opened, no filename was defined (with the C<-file>
option) when the object was constructed, or an error occurred while
reading.
If an error occurs while parsing the INI file the @Config::IniFiles::errors
array will contain messages that might help you figure out where the
problem is in the file.
=cut
# Auxillary function to make deep (aliasing-free) copies of data
# structures. Ignores blessed objects in tree (could be taught not
# to, if needed)
sub _deepcopy {
my $ref=shift;
if (! ref($ref)) { return $ref; }
local $_;
if (UNIVERSAL::isa($ref, "ARRAY")) {
return [map {_deepcopy($_)} @$ref];
}
if (UNIVERSAL::isa($ref, "HASH")) {
my $return={};
foreach my $k (keys %$ref) {
$return->{$k}=_deepcopy($ref->{$k});
}
return $return;
}
carp "Unhandled data structure in $ref, cannot _deepcopy()";
}
# Internal method, gets the next line, taking proper care of line endings.
sub _nextline {
my ($self, $fh)=@_;
local $_;
if (!exists $self->{line_ends}) {
# no $self->{line_ends} is a hint set by caller that we are at
# the first line (kludge kludge).
{
local $/=\1;
my $nextchar;
do {
$nextchar=<$fh>;
return undef if (!defined $nextchar);
$_ .= $nextchar;
} until (m/((\015|\012|\025|\n)$)/s);
$self->{line_ends}=$1;
if ($nextchar eq "\x0d") {
# peek at the next char
$nextchar = <$fh>;
if ($nextchar eq "\x0a") {
$self->{line_ends} .= "\x0a";
} else {
seek $fh, -1, 1;
}
}
}
# If there's a UTF BOM (Byte-Order-Mark) in the first
# character of the first line then remove it before processing
# (http://www.unicode.org/unicode/faq/utf_bom.html#22)
s/^//;
return $_;
} else {
local $/=$self->{line_ends};
return scalar <$fh>;
}
}
# Internal method, closes or resets the file handle. To be called
# whenever ReadConfig() returns.
sub _rollback {
my ($self, $fh)=@_;
# Only close if this is a filename, if it's
# an open handle, then just roll back to the start
if( !ref($self->{cf}) ) {
close($fh);
} else {
# Attempt to rollback to beginning, no problem if this fails (e.g. STDIN)
seek( $fh, 0, 0 );
} # end if
}
sub ReadConfig {
my $self = shift;
my($lineno, $sect);
my($group, $groupmem);
my($parm, $val);
my @cmts;
my $end_comment;
@Config::IniFiles::errors = ( );
# Initialize (and clear out) storage hashes
$self->{sects} = [];
$self->{parms} = {};
$self->{group} = {};
$self->{v} = {};
$self->{sCMT} = {};
$self->{pCMT} = {};
$self->{EOT} = {};
$self->{mysects} = []; # A pair of hashes to remember which params are loaded
$self->{myparms} = {}; # or set using the API vs. imported - useful for
$self->{peCMT} = {}; # this will store trailing comments at the end of single-lined params
# import shadowing, see below, and WriteConfig(-delta=>1)
if( defined $self->{imported} ) {
# Run up the import tree to the top, then reload coming
# back down, maintaining the imported file names and our
# file name.
# This is only needed on a re-load though
$self->{imported}->ReadConfig() unless ($self->{firstload});
foreach my $field (qw(sects parms group v sCMT pCMT EOT)) {
$self->{$field} = _deepcopy($self->{imported}->{$field});
}
} # end if
return 1 if (
(not exists $self->{cf}) or
(not defined $self->{cf}) or
($self->{cf} eq '')
);
my $nocase = $self->{nocase};
my $end_commenthandle = $self->{handle_trailing_comment};
# If this is a reload and we want warnings then send one to the STDERR log
unless( $self->{firstload} || !$self->{reloadwarn} ) {
my ($ss, $mm, $hh, $DD, $MM, $YY) = (localtime(time))[0..5];
printf STDERR
"PID %d reloading config file %s at %d.%02d.%02d %02d:%02d:%02d\n",
$$, $self->{cf}, $YY+1900, $MM+1, $DD, $hh, $mm, $ss;
}
# Turn off. Future loads are reloads
$self->{firstload} = 0;
# Get a filehandle, allowing almost any type of 'file' parameter
my $fh = $self->_make_filehandle( $self->{cf} );
if (!$fh) {
carp "Failed to open $self->{cf}: $!";
return undef;
}
# Get mod time of file so we can retain it (if not from STDIN)
# also check if it's a real file (could have been a filehandle made from a scalar).
if (ref($fh) ne "IO::Scalar" && -e $fh)
{
my @stats = stat $fh;
$self->{file_mode} = sprintf("%04o", $stats[2]) if defined $stats[2];
}
# The first lines of the file must be blank, comments or start with [
my $first = '';
my $allCmt = $self->{allowed_comment_char};
local $_;
delete $self->{line_ends}; # Marks start of parsing for _nextline()
while ( defined($_ = $self->_nextline($fh)) ) {
s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s)
$lineno++;
if (/^\s*$/) { # ignore blank lines
next;
}
elsif (/^\s*[$allCmt]/) { # collect comments
if ($self->{negativedeltas} &&
m/^$self->{comment_char} (.*) is deleted$/) {
my $todelete=$1;
if ($todelete =~ m/^\[(.*)\]$/) {
$self->DeleteSection($1);
} else {
$self->delval($sect, $todelete);
}
} else {
CORE::push(@cmts, $_);
}
next;
}
elsif (/^\s*\[\s*(\S|\S.*\S)\s*\]\s*$/) { # New Section
$sect = $1;
if ($self->{nocase}) {
$sect = lc($sect);
}
$self->AddSection($sect);
$self->SetSectionComment($sect, @cmts);
@cmts = ();
}
elsif (($parm, $val) = /^\s*([^=]*?[^=\s])\s*=\s*(.*)$/) { # new parameter
if ((!defined($sect)) and defined($self->{fallback}))
{
$sect = $self->{fallback};
$self->{fallback_used}++;
}
if (!defined $sect) {
CORE::push(@Config::IniFiles::errors, sprintf('%d: %s', $lineno,
qq#parameter found outside a section#));
$self->_rollback($fh);
return undef;
}
$parm = lc($parm) if $nocase;
my @val = ( );
my $eotmark;
if ($val =~ /^<<(.*)$/) { # "here" value
$eotmark = $1;
my $foundeot = 0;
my $startline = $lineno;
while ( defined($_=$self->_nextline($fh)) ) {
s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s)
$lineno++;
if ($_ eq $eotmark) {
$foundeot = 1;
last;
} else {
# Untaint
/(.*)/ms;
CORE::push(@val, $1);
}
}
if (! $foundeot) {
CORE::push(@Config::IniFiles::errors, sprintf('%d: %s', $startline,
qq#no end marker ("$eotmark") found#));
$self->_rollback();
return undef;
}
} else { # no here value
# process continuation lines, if any
while($self->{allowcontinue} && $val =~ s/\\$//) {
$_ = $self->_nextline($fh);
s/(\015\012?|\012|\025|\n)$//; # remove line ending char(s)
$lineno++;
$val .= $_;
}
# we should split value and comments if there is any comment
if ($end_commenthandle &&
$val =~ /(.*?)\s*[$allCmt]\s*([^$allCmt\s]*)$/) {
$val = $1;
$end_comment = $2;
} else {
$end_comment = "";
}
@val = $val;
}
# Now load value
if (exists $self->{v}{$sect}{$parm} &&
exists $self->{myparms}{$sect} &&
grep( /^\Q$parm\E$/, @{$self->{myparms}{$sect}}) ) {
$self->push($sect, $parm, @val);
} else {
# Loaded parameters shadow imported ones, instead of appending
# to them
$self->newval($sect, $parm, @val);
}
$self->SetParameterComment($sect, $parm, @cmts);
@cmts = ( );
$self->SetParameterEOT($sect,$parm,$eotmark) if (defined $eotmark);
# if handle_trailing_comment is off, this line makes no sense, since all $end_comment=""
$self->SetParameterTrailingComment($sect, $parm, $end_comment);
} else {
CORE::push(@Config::IniFiles::errors, sprintf("Line \%d in file " . $self->{cf} . " is mal-formed:\n\t\%s", $lineno, $_));
}
} # End main parsing loop
# Special case: return undef if file is empty. (suppress this line to
# restore the more intuitive behaviour of accepting empty files)
if (! keys %{$self->{v}} && ! $self->{allowempty}) {
CORE::push @Config::IniFiles::errors, "Empty file treated as error";
$self->_rollback($fh);
return undef;
}
if( defined (my $defaultsect=$self->{startup_settings}->{-default}) ) {
$self->AddSection($defaultsect);
} # end if
$self->_SetEndComments(@cmts);
$self->_rollback($fh);
@Config::IniFiles::errors ? undef : 1;
}
=head2 Sections
Returns an array containing section names in the configuration file.
If the I<nocase> option was turned on when the config object was
created, the section names will be returned in lowercase.
=cut
sub Sections {
my $self = shift;
return @{$self->{sects}} if ref $self->{sects} eq 'ARRAY';
return ();
}
=head2 SectionExists ( $sect_name )
Returns 1 if the specified section exists in the INI file, 0 otherwise (undefined if section_name is not defined).
=cut
sub SectionExists {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
return undef() if not defined $sect;
return 1 if (grep {/^\Q$sect\E$/} @{$self->{sects}});
return 0;
}
=head2 AddSection ( $sect_name )
Ensures that the named section exists in the INI file. If the section already
exists, nothing is done. In this case, the "new" section will possibly contain
data already.
If you really need to have a new section with no parameters in it, check that
the name that you're adding isn't in the list of sections already.
=cut
sub AddSection {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
return if $self->SectionExists($sect);
CORE::push @{$self->{sects}}, $sect unless
grep /^\Q$sect\E$/, @{$self->{sects}};
$self->_touch_section($sect);
$self->SetGroupMember($sect);
# Set up the parameter names and values lists
$self->{parms}{$sect} = [] unless ref $self->{parms}{$sect} eq 'ARRAY';
if (!defined($self->{v}{$sect})) {
$self->{sCMT}{$sect} = [];
$self->{pCMT}{$sect} = {}; # Comments above parameters
$self->{parms}{$sect} = [];
$self->{v}{$sect} = {};
}
}
# Marks a section as modified by us (this includes deleted by us).
sub _touch_section {
my ($self, $sect)=@_;
$self->{mysects} ||= [];
CORE::push @{$self->{mysects}}, $sect unless
grep /^\Q$sect\E$/, @{$self->{mysects}};
}
# Marks a parameter as modified by us (this includes deleted by us).
sub _touch_parameter {
my ($self, $sect, $parm)=@_;
$self->_touch_section($sect);
return if (!exists $self->{v}{$sect});
$self->{myparms}{$sect} ||= [];
CORE::push @{$self->{myparms}{$sect}}, $parm unless
grep /^\Q$parm\E$/, @{$self->{myparms}{$sect}};
}
=head2 DeleteSection ( $sect_name )
Completely removes the entire section from the configuration.
=cut
sub DeleteSection {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
# This is done the fast way, change if data structure changes!!
delete $self->{v}{$sect};
delete $self->{sCMT}{$sect};
delete $self->{pCMT}{$sect};
delete $self->{EOT}{$sect};
delete $self->{parms}{$sect};
delete $self->{myparms}{$sect};
@{$self->{sects}} = grep !/^\Q$sect\E$/, @{$self->{sects}};
$self->_touch_section($sect);
if( $sect =~ /^(\S+)\s+\S+/ ) {
my $group = $1;
if( defined($self->{group}{$group}) ) {
@{$self->{group}{$group}} = grep !/^\Q$sect\E$/, @{$self->{group}{$group}};
} # end if
} # end if
return 1;
} # end DeleteSection
=head2 Parameters ($sect_name)
Returns an array containing the parameters contained in the specified
section.
=cut
sub Parameters {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
return @{$self->{parms}{$sect}} if ref $self->{parms}{$sect} eq 'ARRAY';
return ();
}
=head2 Groups
Returns an array containing the names of available groups.
Groups are specified in the config file as new sections of the form
[GroupName MemberName]
This is useful for building up lists. Note that parameters within a
"member" section are referenced normally (i.e., the section name is
still "Groupname Membername", including the space) - the concept of
Groups is to aid people building more complex configuration files.
=cut
sub Groups {
my $self = shift;
return keys %{$self->{group}} if ref $self->{group} eq 'HASH';
return ();
}
=head2 SetGroupMember ( $sect )
Makes sure that the specified section is a member of the appropriate group.
Only intended for use in newval.
=cut
sub SetGroupMember {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
return(1) unless $sect =~ /^(\S+)\s+\S+/;
my $group = $1;
if (not exists($self->{group}{$group})) {
$self->{group}{$group} = [];
}
if (not grep {/^\Q$sect\E$/} @{$self->{group}{$group}}) {
CORE::push @{$self->{group}{$group}}, $sect;
}
}
=head2 RemoveGroupMember ( $sect )
Makes sure that the specified section is no longer a member of the
appropriate group. Only intended for use in DeleteSection.
=cut
sub RemoveGroupMember {
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
return(1) unless $sect =~ /^(\S+)\s+\S+/;
my $group = $1;
return unless exists $self->{group}{$group};
@{$self->{group}{$group}} = grep {!/^\Q$sect\E$/} @{$self->{group}{$group}};
}
=head2 GroupMembers ($group)
Returns an array containing the members of specified $group. Each element
of the array is a section name. For example, given the sections
[Group Element 1]
...
[Group Element 2]
...
GroupMembers would return ("Group Element 1", "Group Element 2").
=cut
sub GroupMembers {
my $self = shift;
my $group = shift;
return undef if not defined $group;
if ($self->{nocase}) {
$group = lc($group);
}
return @{$self->{group}{$group}} if ref $self->{group}{$group} eq 'ARRAY';
return ();
}
=head2 SetWriteMode ($mode)
Sets the mode (permissions) to use when writing the INI file.
$mode must be a string representation of the octal mode.
=cut
sub SetWriteMode
{
my $self = shift;
my $mode = shift;
return undef if not defined ($mode);
return undef if not ($mode =~ m/[0-7]{3,3}/);
$self->{file_mode} = $mode;
return $mode;
}
=head2 GetWriteMode ($mode)
Gets the current mode (permissions) to use when writing the INI file.
$mode is a string representation of the octal mode.
=cut
sub GetWriteMode
{
my $self = shift;
return undef if not exists $self->{file_mode};
return $self->{file_mode};
}
=head2 WriteConfig ($filename [, %options])
Writes out a new copy of the configuration file. A temporary file
(ending in '-new') is written out and then renamed to the specified
filename. Also see B<BUGS> below.
If C<-delta> is set to a true value in %options, and this object was
imported from another (see L</new>), only the differences between this
object and the imported one will be recorded. Negative deltas will be
encoded into comments, so that a subsequent invocation of I<new()>
with the same imported object produces the same results (see the
I<-negativedeltas> option in L</new>).
C<%options> is not required.
Returns true on success, C<undef> on failure.
=cut
sub WriteConfig {
my ($self, $file, %parms)=@_;
%parms = () unless %parms;
return undef unless defined $file;
# If we are using a filename, then do mode checks and write to a
# temporary file to avoid a race condition
if( !ref($file) ) {
if (-e $file) {
if (not (-w $file))
{
#carp "File $file is not writable. Refusing to write config";
return undef;
}
my $mode = (stat $file)[2];
$self->{file_mode} = sprintf "%04o", ($mode & 0777);
#carp "Using mode $self->{file_mode} for file $file";
} elsif (defined($self->{file_mode}) and not (oct($self->{file_mode}) & 0222)) {
#carp "Store mode $self->{file_mode} prohibits writing config";
}
my $new_file = $file . "-new";
local(*F);
open(F, "> $new_file") || do {
carp "Unable to write temp config file $new_file: $!";
return undef;
};
my $oldfh = select(F);
$self->OutputConfig($parms{-delta});
close(F);
select($oldfh);
rename( $new_file, $file ) || do {
carp "Unable to rename temp config file ($new_file) to $file: $!";
return undef;
};
if (exists $self->{file_mode}) {
chmod oct($self->{file_mode}), $file;
}
} # Otherwise, reset to the start of the file and write, unless we are using STDIN
else {
# Get a filehandle, allowing almost any type of 'file' parameter
## NB: If this were a filename, this would fail because _make_file
## opens a read-only handle, but we have already checked that case
## so re-using the logic is ok [JW/WADG]
my $fh = $self->_make_filehandle( $file );
if (!$fh) {
carp "Could not find a filehandle for the input stream ($file): $!";
return undef;
}
# Only roll back if it's not STDIN (if it is, Carp)
if( $fh == \*STDIN ) {
carp "Cannot write configuration file to STDIN.";
} else {
seek( $fh, 0, 0 );
my $oldfh = select($fh);
$self->OutputConfig($parms{-delta});
seek( $fh, 0, 0 );
select($oldfh);
} # end if
} # end if (filehandle/name)
return 1;
}
=head2 RewriteConfig
Same as WriteConfig, but specifies that the original configuration
file should be rewritten.
=cut
sub RewriteConfig {
my $self = shift;
return undef if (
(not exists $self->{cf}) or
(not defined $self->{cf}) or
($self->{cf} eq '')
);
# Return whatever WriteConfig returns :)
$self->WriteConfig($self->{cf});
}
=head2 GetFileName
Returns the filename associated with this INI file.
If no filename has been specified, returns undef.
=cut
sub GetFileName
{
my $self = shift;
my $filename;
if (exists $self->{cf}) {
$filename = $self->{cf};
} else {
undef $filename;
}
return $filename;
}
=head2 SetFileName ($filename)
If you created the Config::IniFiles object without initialising from
a file, or if you just want to change the name of the file to use for
ReadConfig/RewriteConfig from now on, use this method.
Returns $filename if that was a valid name, undef otherwise.
=cut
sub SetFileName {
my $self = shift;
my $newfile = shift;
return undef if not defined $newfile;
if ($newfile ne "") {
$self->{cf} = $newfile;
return $self->{cf};
}
return undef;
}
=head2 $ini->OutputConfig($delta)
Writes OutputConfig to STDOUT. Use select() to redirect STDOUT to
the output target before calling this function. Optional argument
should be set to 1 if writing only delta.
=cut
sub _OutputParam {
my ($self, $sect, $parm, $val, $ors, $end_comment, $output_cb) = @_;
if (! @$val) {
# An empty variable - see:
# https://rt.cpan.org/Public/Bug/Display.html?id=68554
$output_cb->("$parm=");
$output_cb->("$ors");
}
elsif ((@$val == 1) or $self->{nomultiline}) {
my $cnt = 0;
foreach (@{$val}) {
$cnt++;
$output_cb->("$parm=$_");
# output trailing comment at the last parameter
if ($end_comment && $cnt == @$val) {
$output_cb->(" $self->{comment_char} $end_comment")
}
$output_cb->("$ors");
}
}
else
{
my $eotmark = $self->{EOT}{$sect}{$parm} || 'EOT';
# Make sure the $eotmark does not occur inside the string.
my @letters = ('A' .. 'Z');
my $joined_val = join(q{ }, @$val);
while (index($joined_val, $eotmark) >= 0)
{
$eotmark .= $letters[rand(@letters)];
}
$output_cb->("$parm= <<$eotmark$ors");
my $cnt = 0;
foreach (@{$val}) {
$cnt++;
$output_cb->("$_");
# output trailing comment at the last parameter
if ($end_comment && $cnt == @$val) {
$output_cb->(" $self->{comment_char} $end_comment")
}
$output_cb->("$ors");
}
$output_cb->("$eotmark$ors");
}
return;
}
sub OutputConfig {
my ($self, $delta) = @_;
my($sect, $parm, @cmts);
my $ors = $self->{line_ends} || $\ || "\n"; # $\ is normally unset, but use input by default
my $notfirst = 0;
local $_;
SECT:
foreach $sect (@{$self->{$delta ? "mysects" : "sects"}}) {
if (!defined $self->{v}{$sect}) {
if ($delta) {
print "$self->{comment_char} [$sect] is deleted$ors";
} else {
warn "Weird unknown section $sect" if $^W;
}
next SECT;
}
next unless defined $self->{v}{$sect};
print $ors if $notfirst;
$notfirst = 1;
if ((ref($self->{sCMT}{$sect}) eq 'ARRAY') &&
(@cmts = @{$self->{sCMT}{$sect}})) {
foreach (@cmts) {
print "$_$ors";
}
}
if (!
($self->{fallback_used} and $sect eq $self->{fallback})
)
{
print "[$sect]$ors";
}
next unless ref $self->{v}{$sect} eq 'HASH';
PARM:
foreach $parm (@{$self->{$delta ? "myparms" : "parms"}{$sect}}) {
if (!defined $self->{v}{$sect}{$parm}) {
if ($delta) {
print "$self->{comment_char} $parm is deleted$ors";
} else {
warn "Weird unknown parameter $parm" if $^W;
}
next PARM;
}
if ((ref($self->{pCMT}{$sect}{$parm}) eq 'ARRAY') &&
(@cmts = @{$self->{pCMT}{$sect}{$parm}})) {
foreach (@cmts) {
print "$_$ors";
}
}
my $val = $self->{v}{$sect}{$parm};
my $end_comment = $self->{peCMT}{$sect}{$parm};
next if ! defined ($val); # No parameter exists !!
$self->_OutputParam(
$sect,
$parm,
((ref($val) eq 'ARRAY')
? $val
: [split /[$ors]/, $val, -1]
),
$ors,
defined $end_comment ? $end_comment : "",
sub { print @_; },
);
}
}
foreach my $comment ($self->_GetEndComments()) {
print "$comment$ors";
}
return 1;
}
=head2 SetSectionComment($section, @comment)
Sets the comment for section $section to the lines contained in @comment.
Each comment line will be prepended with the comment character (default
is C<#>) if it doesn't already have a comment character (ie: if the
line does not start with whitespace followed by an allowed comment
character, default is C<#> and C<;>).
To clear a section comment, use DeleteSectionComment ($section)
=cut
sub SetSectionComment
{
my $self = shift;
my $sect = shift;
my @comment = @_;
return undef if not defined $sect;
return undef unless @comment;
if ($self->{nocase}) {
$sect = lc($sect);
}
$self->_touch_section($sect);
$self->{sCMT}{$sect} = [];
# At this point it's possible to have a comment for a section that
# doesn't exist. This comment will not get written to the INI file.
CORE::push @{$self->{sCMT}{$sect}}, $self->_markup_comments(@comment);
return scalar @comment;
}
# this helper makes sure that each line is preceded with the correct comment
# character
sub _markup_comments
{
my $self = shift;
my @comment = @_;
my $allCmt = $self->{allowed_comment_char};
my $cmtChr = $self->{comment_char};
foreach (@comment) {
m/^\s*[$allCmt]/ or ($_ = "$cmtChr $_");
}
@comment;
}
=head2 GetSectionComment ($section)
Returns a list of lines, being the comment attached to section $section. In
scalar context, returns a string containing the lines of the comment separated
by newlines.
The lines are presented as-is, with whatever comment character was originally
used on that line.
=cut
sub GetSectionComment
{
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
if (exists $self->{sCMT}{$sect}) {
my @ret = @{$self->{sCMT}{$sect}};
if (wantarray()) {
return @ret;
}
else {
if (defined ($/)) {
return join "$/", @ret;
} else {
return join "\n", @ret;
}
}
} else {
return undef;
}
}
=head2 DeleteSectionComment ($section)
Removes the comment for the specified section.
=cut
sub DeleteSectionComment
{
my $self = shift;
my $sect = shift;
return undef if not defined $sect;
if ($self->{nocase}) {
$sect = lc($sect);
}
$self->_touch_section($sect);
delete $self->{sCMT}{$sect};
}
=head2 SetParameterComment ($section, $parameter, @comment)
Sets the comment attached to a particular parameter.
Any line of @comment that does not have a comment character will be
prepended with one. See L</SetSectionComment($section, @comment)> above
=cut
sub SetParameterComment
{
my $self = shift;
my $sect = shift;
my $parm = shift;
my @comment = @_;
defined($sect) || return undef;
defined($parm) || return undef;
@comment || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
$self->_touch_parameter($sect, $parm);
if (not exists $self->{pCMT}{$sect}) {
$self->{pCMT}{$sect} = {};
}
$self->{pCMT}{$sect}{$parm} = [];
# Note that at this point, it's possible to have a comment for a parameter,
# without that parameter actually existing in the INI file.
CORE::push @{$self->{pCMT}{$sect}{$parm}}, $self->_markup_comments(@comment);
return scalar @comment;
}
sub _SetEndComments
{
my $self = shift;
my @comments = @_;
$self->{_comments_at_end_of_file} = \@comments;
return 1;
}
sub _GetEndComments {
my $self = shift;
return @{$self->{_comments_at_end_of_file}};
}
=head2 GetParameterComment ($section, $parameter)
Gets the comment attached to a parameter. In list context returns all
comments - in scalar context returns them joined by newlines.
=cut
sub GetParameterComment
{
my $self = shift;
my $sect = shift;
my $parm = shift;
defined($sect) || return undef;
defined($parm) || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
};
exists($self->{pCMT}{$sect}) || return undef;
exists($self->{pCMT}{$sect}{$parm}) || return undef;
my @comment = @{$self->{pCMT}{$sect}{$parm}};
return wantarray() ? @comment : join((defined $/ ? $/ : "\n"), @comment);
}
=head2 DeleteParameterComment ($section, $parmeter)
Deletes the comment attached to a parameter.
=cut
sub DeleteParameterComment
{
my $self = shift;
my $sect = shift;
my $parm = shift;
defined($sect) || return undef;
defined($parm) || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
};
# If the parameter doesn't exist, our goal has already been achieved
exists($self->{pCMT}{$sect}) || return 1;
exists($self->{pCMT}{$sect}{$parm}) || return 1;
$self->_touch_parameter($sect, $parm);
delete $self->{pCMT}{$sect}{$parm};
return 1;
}
=head2 GetParameterEOT ($section, $parameter)
Accessor method for the EOT text (in fact, style) of the specified parameter. If any text is used as an EOT mark, this will be returned. If the parameter was not recorded using HERE style multiple lines, GetParameterEOT returns undef.
=cut
sub GetParameterEOT
{
my $self = shift;
my $sect = shift;
my $parm = shift;
defined($sect) || return undef;
defined($parm) || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
};
if (not exists $self->{EOT}{$sect}) {
$self->{EOT}{$sect} = {};
}
if (not exists $self->{EOT}{$sect}{$parm}) {
return undef;
}
return $self->{EOT}{$sect}{$parm};
}
=head2 $cfg->SetParameterEOT ($section, $parameter, $EOT)
Accessor method for the EOT text for the specified parameter. Sets the HERE style marker text to the value $EOT. Once the EOT text is set, that parameter will be saved in HERE style.
To un-set the EOT text, use DeleteParameterEOT ($section, $parameter).
=cut
sub SetParameterEOT
{
my $self = shift;
my $sect = shift;
my $parm = shift;
my $EOT = shift;
defined($sect) || return undef;
defined($parm) || return undef;
defined($EOT) || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
};
$self->_touch_parameter($sect, $parm);
if (not exists $self->{EOT}{$sect}) {
$self->{EOT}{$sect} = {};
}
$self->{EOT}{$sect}{$parm} = $EOT;
}
=head2 DeleteParameterEOT ($section, $parmeter)
Removes the EOT marker for the given section and parameter.
When writing a configuration file, if no EOT marker is defined
then "EOT" is used.
=cut
sub DeleteParameterEOT
{
my $self = shift;
my $sect = shift;
my $parm = shift;
defined($sect) || return undef;
defined($parm) || return undef;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
$self->_touch_parameter($sect, $parm);
delete $self->{EOT}{$sect}{$parm};
}
=head2 SetParameterTrailingComment ($section, $parameter, $cmt)
Set the end trailing comment for the given section and parameter.
If there is a old comment for the parameter, it will be
overwritten by the new one.
If there is a new parameter trailing comment to be added, the
value should be added first.
=cut
sub SetParameterTrailingComment
{
my $self = shift;
my $sect = shift;
my $parm = shift;
my $cmt = shift;
return undef if not defined $sect;
return undef if not defined $parm;
return undef if not defined $cmt;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
# confirm the parameter exist
return undef if not exists $self->{v}{$sect}{$parm};
$self->_touch_parameter($sect, $parm);
$self->{peCMT}{$sect}{$parm} = $cmt;
1;
}
=head2 GetParameterTrailingComment ($section, $parameter)
An accessor method to read the trailing comment after the parameter.
The trailing comment will be returned if there is one. A null string
will be returned if the parameter exists but no comment for it.
otherwise, L<undef> will be returned.
=cut
sub GetParameterTrailingComment
{
my $self = shift;
my $sect = shift;
my $parm = shift;
return undef if not defined $sect;
return undef if not defined $parm;
if ($self->{nocase}) {
$sect = lc($sect);
$parm = lc($parm);
}
# confirm the parameter exist
return undef if not exists $self->{v}{$sect}{$parm};
return $self->{peCMT}{$sect}{$parm};
}
=head2 Delete
Deletes the entire configuration file in memory.
=cut
sub Delete {
my $self = shift;
foreach my $section ($self->Sections()) {
$self->DeleteSection($section);
}
return 1;
} # end Delete
=head1 USAGE -- Tied Hash
=head2 tie %ini, 'Config::IniFiles', (-file=>$filename, [-option=>value ...] )
Using C<tie>, you can tie a hash to a B<Config::IniFiles> object. This creates a new
object which you can access through your hash, so you use this instead of the
B<new> method. This actually creates a hash of hashes to access the values in
the INI file. The options you provide through C<tie> are the same as given for
the B<new> method, above.
Here's an example:
use Config::IniFiles;
my %ini
tie %ini, 'Config::IniFiles', ( -file => "/path/configfile.ini" );
print "We have $ini{Section}{Parameter}." if $ini{Section}{Parameter};
Accessing and using the hash works just like accessing a regular hash and
many of the object methods are made available through the hash interface.
For those methods that do not coincide with the hash paradigm, you can use
the Perl C<tied> function to get at the underlying object tied to the hash
and call methods on that object. For example, to write the hash out to a new
ini file, you would do something like this:
tied( %ini )->WriteConfig( "/newpath/newconfig.ini" ) ||
die "Could not write settings to new file.";
=head2 $val = $ini{$section}{$parameter}
Returns the value of $parameter in $section.
Multiline values accessed through a hash will be returned
as a list in list context and a concatenated value in scalar
context.
=head2 $ini{$section}{$parameter} = $value;
Sets the value of C<$parameter> in C<$section> to C<$value>.
To set a multiline or multiv-alue parameter just assign an
array reference to the hash entry, like this:
$ini{$section}{$parameter} = [$value1, $value2, ...];
If the parameter did not exist in the original file, it will
be created. However, Perl does not seem to extend autovivification
to tied hashes. That means that if you try to say
$ini{new_section}{new_paramters} = $val;
and the section 'new_section' does not exist, then Perl won't
properly create it. In order to work around this you will need
to create a hash reference in that section and then assign the
parameter value. Something like this should do nicely:
$ini{new_section} = {};
$ini{new_section}{new_paramters} = $val;
=head2 %hash = %{$ini{$section}}
Using the tie interface, you can copy whole sections of the
ini file into another hash. Note that this makes a copy of
the entire section. The new hash in no longer tied to the
ini file, In particular, this means -default and -nocase
settings will not apply to C<%hash>.
=head2 $ini{$section} = {}; %{$ini{$section}} = %parameters;
Through the hash interface, you have the ability to replace
the entire section with a new set of parameters. This call
will fail, however, if the argument passed in NOT a hash
reference. You must use both lines, as shown above so that
Perl recognizes the section as a hash reference context
before COPYing over the values from your C<%parameters> hash.
=head2 delete $ini{$section}{$parameter}
When tied to a hash, you can use the Perl C<delete> function
to completely remove a parameter from a section.
=head2 delete $ini{$section}
The tied interface also allows you to delete an entire
section from the ini file using the Perl C<delete> function.
=head2 %ini = ();
If you really want to delete B<all> the items in the ini file, this
will do it. Of course, the changes won't be written to the actual
file unless you call B<RewriteConfig> on the object tied to the hash.
=head2 Parameter names
=over 4
=item my @keys = keys %{$ini{$section}}
=item while (($k, $v) = each %{$ini{$section}}) {...}
=item if( exists %{$ini{$section}}, $parameter ) {...}
=back
When tied to a hash, you use the Perl C<keys> and C<each>
functions to iteratively list the parameters (C<keys>) or
parameters and their values (C<each>) in a given section.
You can also use the Perl C<exists> function to see if a
parameter is defined in a given section.
Note that none of these will return parameter names that
are part of the default section (if set), although accessing
an unknown parameter in the specified section will return a
value from the default section if there is one.
=head2 Section names
=over 4
=item foreach( keys %ini ) {...}
=item while (($k, $v) = each %ini) {...}
=item if( exists %ini, $section ) {...}
=back
When tied to a hash, you use the Perl C<keys> and C<each>
functions to iteratively list the sections in the ini file.
You can also use the Perl C<exists> function to see if a
section is defined in the file.
=cut
############################################################
#
# TIEHASH Methods
#
# Description:
# These methods allow you to tie a hash to the
# Config::IniFiles object. Note that, when tied, the
# user wants to look at thinks like $ini{sec}{parm}, but the
# TIEHASH only provides one level of hash interace, so the
# root object gets asked for a $ini{sec}, which this
# implements. To further tie the {parm} hash, the internal
# class Config::IniFiles::_section, is provided, below.
#
############################################################
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub TIEHASH {
my $class = shift;
my %parms = @_;
# Get a new object
my $self = $class->new( %parms );
return $self;
} # end TIEHASH
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub FETCH {
my $self = shift;
my( $key ) = @_;
$key = lc($key) if( $self->{nocase} );
return if (! $self->{v}{$key});
my %retval;
tie %retval, 'Config::IniFiles::_section', $self, $key;
return \%retval;
} # end FETCH
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000Jun14 Fixed bug where wrong ref was saved JW
# 2000Oct09 Fixed possible but in %parms with defaults JW
# 2001Apr04 Fixed -nocase problem in storing JW
# ----------------------------------------------------------
sub STORE {
my $self = shift;
my( $key, $ref ) = @_;
return undef unless ref($ref) eq 'HASH';
$key = lc($key) if( $self->{nocase} );
$self->AddSection($key);
$self->{v}{$key} = {%$ref};
$self->{parms}{$key} = [keys %$ref];
$self->{myparms}{$key} = [keys %$ref];
1;
} # end STORE
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# 2000Dec17 Now removes comments, groups and EOTs too JW
# 2001Arp04 Fixed -nocase problem JW
# ----------------------------------------------------------
sub DELETE {
my $self = shift;
my( $key ) = @_;
my $retval=$self->FETCH($key);
$self->DeleteSection($key);
return $retval;
} # end DELETE
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub CLEAR {
my $self = shift;
return $self->Delete();
} # end CLEAR
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub FIRSTKEY {
my $self = shift;
$self->{tied_enumerator}=0;
return $self->NEXTKEY();
} # end FIRSTKEY
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub NEXTKEY {
my $self = shift;
my( $last ) = @_;
my $i=$self->{tied_enumerator}++;
my $key=$self->{sects}[$i];
return if (! defined $key);
return wantarray ? ($key, $self->FETCH($key)) : $key;
} # end NEXTKEY
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# 2001Apr04 Fixed -nocase bug and false true bug JW
# ----------------------------------------------------------
sub EXISTS {
my $self = shift;
my( $key ) = @_;
return $self->SectionExists($key);
} # end EXISTS
# ----------------------------------------------------------
# DESTROY is used by TIEHASH and the Perl garbage collector,
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000May09 Created method JW
# ----------------------------------------------------------
sub DESTROY {
# my $self = shift;
} # end if
# ----------------------------------------------------------
# Sub: _make_filehandle
#
# Args: $thing
# $thing An input source
#
# Description: Takes an input source of a filehandle,
# filehandle glob, reference to a filehandle glob, IO::File
# object or scalar filename and returns a file handle to
# read from it with.
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 06Dec2001 Added to support input from any source JW
# ----------------------------------------------------------
sub _make_filehandle {
my $self = shift;
#
# This code is 'borrowed' from Lincoln D. Stein's GD.pm module
# with modification for this module. Thanks Lincoln!
#
no strict 'refs';
my $thing = shift;
if (ref($thing) eq "SCALAR") {
if (eval { require IO::Scalar; $IO::Scalar::VERSION >= 2.109; }) {
return IO::Scalar->new($thing);
} else {
warn "SCALAR reference as file descriptor requires IO::stringy ".
"v2.109 or later" if ($^W);
return;
}
}
return $thing if defined(fileno $thing);
# return $thing if defined($thing) && ref($thing) && defined(fileno $thing);
# otherwise try qualifying it into caller's package
my $fh = qualify_to_ref($thing,caller(1));
return $fh if defined(fileno $fh);
# return $fh if defined($thing) && ref($thing) && defined(fileno $fh);
# otherwise treat it as a file to open
$fh = gensym;
open($fh,$thing) || return;
return $fh;
} # end _make_filehandle
############################################################
#
# INTERNAL PACKAGE: Config::IniFiles::_section
#
# Description:
# This package is used to provide a single-level TIEHASH
# interface to the sections in the IniFile. When tied, the
# user wants to look at thinks like $ini{sec}{parm}, but the
# TIEHASH only provides one level of hash interace, so the
# root object gets asked for a $ini{sec} and must return a
# has reference that accurately covers the '{parm}' part.
#
# This package is only used when tied and is inter-woven
# between the sections and their parameters when the TIEHASH
# method is called by Perl. It's a very simple implementation
# of a tied hash object that simply maps onto the object API.
#
############################################################
# Date Modification Author
# ----------------------------------------------------------
# 2000.May.09 Created to excapsulate TIEHASH interface JW
############################################################
package Config::IniFiles::_section;
use strict;
use Carp;
use vars qw( $VERSION );
$Config::IniFiles::_section::VERSION = 2.16;
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::TIEHASH
#
# Args: $class, $config, $section
# $class The class that this is being tied to.
# $config The parent Config::IniFiles object
# $section The section this tied object refers to
#
# Description: Builds the object that implements accesses to
# the tied hash.
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# ----------------------------------------------------------
sub TIEHASH {
my $proto = shift;
my $class = ref($proto) || $proto;
my ($config, $section)=@_;
# Make a new object
return bless {config=>$config, section=>$section}, $class;
} # end TIEHASH
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::FETCH
#
# Args: $key
# $key The name of the key whose value to get
#
# Description: Returns the value associated with $key. If
# the value is a list, returns a list reference.
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2000Jun15 Fixed bugs in -default handler JW
# 2000Dec07 Fixed another bug in -deault handler JW
# 2002Jul04 Returning scalar values (Bug:447532) AS
# ----------------------------------------------------------
sub FETCH {
my ($self, $key)=@_;
my @retval=$self->{config}->val($self->{section}, $key);
return (@retval <= 1) ? $retval[0] : \@retval;
} # end FETCH
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::STORE
#
# Args: $key, @val
# $key The key under which to store the value
# @val The value to store, either an array or a scalar
#
# Description: Sets the value for the specified $key
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2001Apr04 Fixed -nocase bug JW
# ----------------------------------------------------------
sub STORE {
my ($self, $key, @val)=@_;
return $self->{config}->newval($self->{section}, $key, @val);
} # end STORE
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::DELETE
#
# Args: $key
# $key The key to remove from the hash
#
# Description: Removes the specified key from the hash and
# returns its former value.
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2001Apr04 Fixed -nocase bug JW
# ----------------------------------------------------------
sub DELETE {
my ($self, $key)=@_;
my $retval=$self->{config}->val($self->{section}, $key);
$self->{config}->delval($self->{section}, $key);
return $retval;
} # end DELETE
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::CLEAR
#
# Args: (None)
#
# Description: Empties the entire hash
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# ----------------------------------------------------------
sub CLEAR {
my ($self) = @_;
return $self->{config}->DeleteSection($self->{section});
} # end CLEAR
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::EXISTS
#
# Args: $key
# $key The key to look for
#
# Description: Returns whether the key exists
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# 2001Apr04 Fixed -nocase bug JW
# ----------------------------------------------------------
sub EXISTS {
my ($self, $key)=@_;
return $self->{config}->exists($self->{section},$key);
} # end EXISTS
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::FIRSTKEY
#
# Args: (None)
#
# Description: Returns the first key in the hash
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# ----------------------------------------------------------
sub FIRSTKEY {
my $self = shift;
$self->{tied_enumerator}=0;
return $self->NEXTKEY();
} # end FIRSTKEY
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::NEXTKEY
#
# Args: $last
# $last The last key accessed by the interator
#
# Description: Returns the next key in line
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# ----------------------------------------------------------
sub NEXTKEY {
my $self = shift;
my( $last ) = @_;
my $i=$self->{tied_enumerator}++;
my @keys = $self->{config}->Parameters($self->{section});
my $key=$keys[$i];
return if (! defined $key);
return wantarray ? ($key, $self->FETCH($key)) : $key;
} # end NEXTKEY
# ----------------------------------------------------------
# Sub: Config::IniFiles::_section::DESTROY
#
# Args: (None)
#
# Description: Called on cleanup
# ----------------------------------------------------------
# Date Modification Author
# ----------------------------------------------------------
# ----------------------------------------------------------
sub DESTROY {
# my $self = shift
} # end DESTROY
1;
=head1 IMPORT / DELTA FEATURES
The I<-import> option to L</new> allows one to stack one
I<Config::IniFiles> object on top of another (which might be itself
stacked in turn and so on recursively, but this is beyond the
point). The effect, as briefly explained in L</new>, is that the
fields appearing in the composite object will be a superposition of
those coming from the ``original'' one and the lines coming from the
file, the latter taking precedence. For example, let's say that
C<$master> and C<overlay> were created like this:
my $master = Config::IniFiles->new(-file => "master.ini");
my $overlay = Config::IniFiles->new(-file => "overlay.ini",
-import => $master);
If the contents of C<master.ini> and C<overlay.ini> are respectively
; master.ini
[section1]
arg0=unchanged from master.ini
arg1=val1
[section2]
arg2=val2
and
; overlay.ini
[section1]
arg1=overriden
Then C<< $overlay->val("section1", "arg1") >> is "overriden", while
C<< $overlay->val("section1", "arg0") >> is "unchanged from
master.ini".
This feature may be used to ship a ``global defaults'' configuration
file for a Perl application, that can be overridden piecewise by a
much shorter, per-site configuration file. Assuming UNIX-style path
names, this would be done like this:
my $defaultconfig = Config::IniFiles->new
(-file => "/usr/share/myapp/myapp.ini.default");
my $config = Config::IniFiles->new
(-file => "/etc/myapp.ini", -import => $defaultconfig);
# Now use $config and forget about $defaultconfig in the rest of
# the program
Starting with version 2.39, I<Config::IniFiles> also provides features
to keep the importing / per-site configuration file small, by only
saving those options that were modified by the running program. That
is, if one calls
$overlay->setval("section1", "arg1", "anotherval");
$overlay->newval("section3", "arg3", "val3");
$overlay->WriteConfig(-delta=>1);
C<overlay.ini> would now contain
; overlay.ini
[section1]
arg1=anotherval
[section3]
arg3=val3
This is called a I<delta file> (see L</WriteConfig>). The untouched
[section2] and arg0 do not appear, and the config file is therefore
shorter; while of course, reloading the configuration into C<$master>
and C<$overlay>, either through C<< $overlay->ReadConfig() >> or through
the same code as above (e.g. when application restarts), would yield
exactly the same result had the overlay object been saved in whole to
the file system.
The only problem with this delta technique is one cannot delete the
default values in the overlay configuration file, only change
them. This is solved by a file format extension, enabled by the
I<-negativedeltas> option to L</new>: if, say, one would delete
parameters like this,
$overlay->DeleteSection("section2");
$overlay->delval("section1", "arg0");
$overlay->WriteConfig(-delta=>1);
The I<overlay.ini> file would now read:
; overlay.ini
[section1]
; arg0 is deleted
arg1=anotherval
; [section2] is deleted
[section3]
arg3=val3
Assuming C<$overlay> was later re-read with C<< -negativedeltas => 1 >>,
the parser would interpret the deletion comments to yield the correct
result, that is, [section2] and arg0 would cease to exist in the
C<$overlay> object.
=cut
=head1 DIAGNOSTICS
=head2 @Config::IniFiles::errors
Contains a list of errors encountered while parsing the configuration
file. If the I<new> method returns B<undef>, check the value of this
to find out what's wrong. This value is reset each time a config file
is read.
=head1 BUGS
=over 3
=item *
The output from [Re]WriteConfig/OutputConfig might not be as pretty as
it can be. Comments are tied to whatever was immediately below them.
And case is not preserved for Section and Parameter names if the -nocase
option was used.
=item *
No locking is done by [Re]WriteConfig. When writing servers, take
care that only the parent ever calls this, and consider making your
own backup.
=back
=head1 Data Structure
Note that this is only a reference for the package maintainers - one of the
upcoming revisions to this package will include a total clean up of the
data structure.
$iniconf->{cf} = "config_file_name"
->{startup_settings} = \%orginal_object_parameters
->{firstload} = 0 OR 1
->{imported} = $object WHERE $object->isa("Config::IniFiles")
->{nocase} = 0
->{reloadwarn} = 0
->{sects} = \@sections
->{mysects} = \@sections
->{sCMT}{$sect} = \@comment_lines
->{group}{$group} = \@group_members
->{parms}{$sect} = \@section_parms
->{myparms}{$sect} = \@section_parms
->{EOT}{$sect}{$parm} = "end of text string"
->{pCMT}{$sect}{$parm} = \@comment_lines
->{v}{$sect}{$parm} = $value OR \@values
=head1 AUTHOR and ACKNOWLEDGEMENTS
The original code was written by Scott Hutton.
Then handled for a time by Rich Bowen (thanks!),
It is now managed by Jeremy Wadsack,
with many contributions from various other people.
In particular, special thanks go to (in roughly chronological order):
Bernie Cosell, Alan Young, Alex Satrapa, Mike Blazer, Wilbert van de Pieterman,
Steve Campbell, Robert Konigsberg, Scott Dellinger, R. Bernstein,
Daniel Winkelmann, Pires Claudio, Adrian Phillips,
Marek Rouchal, Luc St Louis, Adam Fischler, Kay Röpke, Matt Wilson,
Raviraj Murdeshwar and Slaven Rezic, Florian Pfaff
Geez, that's a lot of people. And apologies to the folks who were missed.
If you want someone to bug about this, that would be:
Jeremy Wadsack <dgsupport at wadsack-allen dot com>
If you want more information, or want to participate, go to:
http://sourceforge.net/projects/config-inifiles/
Please send bug reports to config-inifiles-bugs@lists.sourceforge.net
Development discussion occurs on the mailing list
config-inifiles-dev@lists.sourceforge.net, which you can subscribe
to by going to the project web site (link above).
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
1;
# Please keep the following within the last four lines of the file
#[JW for editor]:mode=perl:tabSize=8:indentSize=2:noTabs=true:indentOnEnter=true:
|