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 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
|
package Contextual::Return;
# Fake out CORE::GLOBAL::caller and Carp very early...
BEGIN {
no warnings 'redefine';
*CORE::GLOBAL::caller = sub {
my ($uplevels) = shift || 0;
return CORE::caller($uplevels + 2 + $Contextual::Return::uplevel)
if $Contextual::Return::uplevel;
return CORE::caller($uplevels + 1);
};
use Carp;
my $real_carp = *Carp::carp{CODE};
my $real_croak = *Carp::croak{CODE};
*Carp::carp = sub {
goto &{$real_carp} if !$Contextual::Return::uplevel;
warn _in_context(@_);
};
*Carp::croak = sub {
goto &{$real_croak} if !$Contextual::Return::uplevel;
die _in_context(@_);
};
}
our $VERSION = '0.003001';
use warnings;
use strict;
sub _in_context {
my $msg = join q{}, @_;
# Start looking in caller...
my $stack_frame = 1;
my ($package, $file, $line, $sub) = CORE::caller($stack_frame++);
my ($orig_package, $prev_package) = ($package) x 2;
my $LOC = qq{at $file line $line};
# Walk up stack...
STACK_FRAME:
while (1) {
my ($package, $file, $line, $sub) = CORE::caller($stack_frame++);
# Fall off the top of the stack...
last if !defined $package;
# Ignore this module (and any helpers)...
next STACK_FRAME if $package =~ m{^Contextual::Return}xms;
# Track the call up the stack...
$LOC = qq{at $file line $line};
# Ignore transitions within original caller...
next STACK_FRAME
if $package eq $orig_package && $prev_package eq $orig_package;
# If we get a transition out of the original package, we're there...
last STACK_FRAME;
}
# Insert location details...
$msg =~ s/<LOC>/$LOC/g or $msg =~ s/[^\S\n]*$/ $LOC/;
$msg =~ s/$/\n/;
return $msg;
}
# Indentation corresponds to inherited fall-back relationships...
my @CONTEXTS = qw(
DEFAULT
VOID
NONVOID
LIST
SCALAR
VALUE
STR
NUM
BOOL
PUREBOOL
REF
SCALARREF
ARRAYREF
CODEREF
HASHREF
GLOBREF
OBJREF
METHOD
);
my %attrs_of;
my @ALL_EXPORTS = (
@CONTEXTS,
qw(
LAZY RESULT RVALUE METHOD FAIL
FIXED RECOVER LVALUE RETOBJ FAIL_WITH
ACTIVE CLEANUP NVALUE
)
);
my %STD_NAME_FOR = map { $_ => $_ } @ALL_EXPORTS;
sub import {
# Load utility module for failure handlers...
if (require Contextual::Return::Failure) {
*FAIL = \&Contextual::Return::Failure::_FAIL;
*FAIL_WITH = \&Contextual::Return::Failure::_FAIL_WITH;
}
# Don't need the package name...
shift @_;
# If args, export nothing by default; otherwise export all...
my %exports = @_ ? () : %STD_NAME_FOR;
# All args are export either selectors and/or renamers...
while (my $selector = shift @_) {
my $next_arg = $_[0];
my $renamer = (defined $next_arg
&& !ref $next_arg
&& !exists $STD_NAME_FOR{$next_arg})
? shift(@_)
: undef;
%exports = (%exports, _add_exports_for($selector, $renamer));
}
# Loop through possible exports, exporting anything requested...
my $caller = CORE::caller;
EXPORT:
for my $subname (keys %exports) {
no strict qw( refs );
*{$caller.'::'.$exports{$subname}} = \&{$subname};
}
};
sub _add_exports_for {
my ($selector, $renamer) = @_;
# If no renamer, use original name...
$renamer ||= '%s';
# Handle different types of selector...
my $selector_type = ref($selector) || 'literal';
# Array selector recursively export each element...
if ($selector_type eq 'ARRAY') {
return map { _add_exports_for($_,$renamer) } @{$selector};
}
elsif ($selector_type eq 'Regexp') {
my @selected = grep {/$selector/} @ALL_EXPORTS;
if (!@selected) {
Carp:carp("use Contextual::Return $selector didn't export anything");
}
return map { $_ => sprintf($renamer, $_) } @selected;
}
elsif ($selector_type eq 'literal') {
Carp::croak "Can't export $selector: no such handler"
if !exists $STD_NAME_FOR{$selector};
return ( $selector => sprintf($renamer, $selector) );
}
else {
Carp::croak "Can't use $selector_type as export specifier";
}
}
# Let handlers access the result object they're inside...
sub RETOBJ() {
our $__RETOBJ__;
return $__RETOBJ__;
}
use Scalar::Util qw( refaddr );
# Override return value in a C::R handler...
sub RESULT(;&) {
my ($block) = @_;
# Determine call context and arg list...
my $context;
my $args = do { package DB; $context=(CORE::caller 1)[5]; \@DB::args };
# No args -> return appropriate value...
if (!@_) {
return $context ? @{ $Contextual::Return::__RESULT__ || [] }
: $Contextual::Return::__RESULT__->[0]
;
}
# Hide from caller() and the enclosing eval{}...
# Evaluate block in context and cache result...
local $Contextual::Return::uplevel = $Contextual::Return::uplevel+1;
$Contextual::Return::__RESULT__
= $context ? [ $block->(@{$args}) ]
: defined $context ? [ scalar $block->(@{$args}) ]
: do { $block->(@{$args}); [] }
;
return;
}
sub RVALUE(&;@) :lvalue;
sub LVALUE(&;@) :lvalue;
sub NVALUE(&;@) :lvalue;
my %opposite_of = (
'RVALUE' => 'LVALUE or NVALUE',
'LVALUE' => 'RVALUE or NVALUE',
'NVALUE' => 'LVALUE or RVALUE',
);
BEGIN {
for my $subname (qw( RVALUE LVALUE NVALUE) ) {
no strict 'refs';
*{$subname} = sub(&;@) :lvalue { # (handler, return_lvalue);
my $handler = shift;
my $impl;
my $args = do{ package DB; ()=CORE::caller(1); \@DB::args };
if (@_==0) {
$impl = tie $_[0], 'Contextual::Return::Lvalue',
$subname => $handler, args=>$args;
}
elsif (@_==1 and $impl = tied $_[0]) {
die _in_context "Can't install two $subname handlers"
if exists $impl->{$subname};
$impl->{$subname} = $handler;
}
else {
my $vals = join q{, }, map { tied $_ ? keys %{tied $_}
: defined $_ ? $_
: 'undef'
} @_;
die _in_context "Expected a $opposite_of{$subname} block ",
"after the $subname block <LOC> ",
"but found instead: $vals\n";
}
# Handle void context calls...
if (!defined wantarray && $impl->{NVALUE}) {
# Fake out caller() and Carp...
local $Contextual::Return::uplevel = 1;
# Call and clear handler...
local $Contextual::Return::__RETOBJ__ = $impl;
$impl->{NVALUE}( @{$impl->{args}} );
delete $impl->{NVALUE};
}
$_[0];
}
}
}
sub FIXED ($) {
my ($crv) = @_;
$attrs_of{refaddr $crv}{FIXED} = 1;
return $crv;
}
sub ACTIVE ($) {
my ($crv) = @_;
$attrs_of{refaddr $crv}{ACTIVE} = 1;
return $crv;
}
sub LIST (;&$) {
my ($block, $crv) = @_;
# Handle simple context tests...
return !!(CORE::caller 1)[5] if !@_;
# Ensure we have an object...
my $attrs;
if (!refaddr $crv) {
my $args = do{ package DB; ()=CORE::caller(1); \@DB::args };
my $subname = (CORE::caller(1))[3];
$crv = bless \my $scalar, 'Contextual::Return::Value';
$attrs = $attrs_of{refaddr $crv} = { args => $args, sub => $subname };
}
else {
$attrs = $attrs_of{refaddr $crv};
}
local $Contextual::Return::__RETOBJ__ = $crv;
# Handle repetitions...
die _in_context "Can't install two LIST handlers"
if exists $attrs->{LIST};
# Identify contexts...
my $wantarray = wantarray;
use Want;
$attrs->{want_pure_bool} ||= Want::want('BOOL');
# Prepare for exception handling...
my $recover = $attrs->{RECOVER};
local $Contextual::Return::uplevel = 2;
# Handle list context directly...
if (wantarray) {
local $Contextual::Return::__RESULT__;
my @rv = eval { $block->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [@rv];
}
() = $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
return @rv if !$Contextual::Return::__RESULT__;
return @{$Contextual::Return::__RESULT__};
}
# Handle void context directly...
if (!defined $wantarray) {
handler:
for my $context (qw< VOID DEFAULT >) {
my $handler = $attrs->{$context} or next;
eval { $attrs->{$context}->(@{$attrs->{args}}) };
if ($recover) {
$recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
last;
}
return;
}
# Otherwise, cache handler...
$attrs->{LIST} = $block;
return $crv;
}
sub VOID (;&$) {
my ($block, $crv) = @_;
# Handle simple context tests...
return !defined( (CORE::caller 1)[5] ) if !@_;
# Ensure we have an object...
my $attrs;
if (!refaddr $crv) {
my $args = do{ package DB; ()=CORE::caller(1); \@DB::args };
my $subname = (CORE::caller(1))[3];
$crv = bless \my $scalar, 'Contextual::Return::Value';
$attrs = $attrs_of{refaddr $crv} = { args => $args, sub => $subname };
}
else {
$attrs = $attrs_of{refaddr $crv};
}
local $Contextual::Return::__RETOBJ__ = $crv;
# Handle repetitions...
die _in_context "Can't install two VOID handlers"
if exists $attrs->{VOID};
# Identify contexts...
my $wantarray = wantarray;
use Want;
$attrs->{want_pure_bool} ||= Want::want('BOOL');
# Prepare for exception handling...
my $recover = $attrs->{RECOVER};
local $Contextual::Return::uplevel = 2;
# Handle list context directly, if possible...
if (wantarray) {
local $Contextual::Return::__RESULT__;
# List or ancestral handlers...
handler:
for my $context (qw(LIST VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
my @rv = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [@rv];
}
() = $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
return @rv if !$Contextual::Return::__RESULT__;
return @{$Contextual::Return::__RESULT__};
}
# Convert to list from arrayref handler...
if (my $handler = $attrs->{ARRAYREF}) {
my $array_ref = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$array_ref];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
# Array ref may be returned directly, or via RESULT{}...
$array_ref = $Contextual::Return::__RESULT__->[0]
if $Contextual::Return::__RESULT__;
return @{$array_ref} if (ref $array_ref||q{}) eq 'ARRAY';
}
# Return scalar object as one-elem list, if possible...
handler:
for my $context (qw(BOOL STR NUM VALUE SCALAR LAZY)) {
return $crv if exists $attrs->{$context};
}
$@ = _in_context "Can't call $attrs->{sub} in list context";
if ($recover) {
() = $recover->(@{$attrs->{args}});
}
else {
die $@;
}
}
# Handle void context directly...
if (!defined $wantarray) {
eval { $block->(@{$attrs->{args}}) };
if ($recover) {
$recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
return;
}
# Otherwise, cache handler...
$attrs->{VOID} = $block;
return $crv;
}
for my $context (qw( SCALAR NONVOID )) {
no strict qw( refs );
*{$context} = sub (;&$) {
my ($block, $crv) = @_;
# Handle simple context tests...
if (!@_) {
my $callers_context = (CORE::caller 1)[5];
return defined $callers_context
&& ($context eq 'NONVOID' || !$callers_context);
}
# Ensure we have an object...
my $attrs;
if (!refaddr $crv) {
my $args = do{ package DB; ()=CORE::caller(1); \@DB::args };
my $subname = (CORE::caller(1))[3];
$crv = bless \my $scalar, 'Contextual::Return::Value';
$attrs = $attrs_of{refaddr $crv}
= { args => $args, sub => $subname };
}
else {
$attrs = $attrs_of{refaddr $crv};
}
local $Contextual::Return::__RETOBJ__ = $crv;
# Make sure this block is a possibility too...
die _in_context "Can't install two $context handlers"
if exists $attrs->{$context};
$attrs->{$context} = $block;
# Identify contexts...
my $wantarray = wantarray;
use Want;
$attrs->{want_pure_bool} ||= Want::want('BOOL');
# Prepare for exception handling...
my $recover = $attrs->{RECOVER};
local $Contextual::Return::uplevel = 2;
# Handle list context directly, if possible...
if (wantarray) {
local $Contextual::Return::__RESULT__;
# List or ancestral handlers...
handler:
for my $context (qw(LIST VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
my @rv = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [@rv];
}
() = $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
return @rv if !$Contextual::Return::__RESULT__;
return @{$Contextual::Return::__RESULT__};
}
# Convert to list from arrayref handler...
if (my $handler = $attrs->{ARRAYREF}) {
my $array_ref = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$array_ref];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
# Array ref may be returned directly, or via RESULT{}...
$array_ref = $Contextual::Return::__RESULT__->[0]
if $Contextual::Return::__RESULT__;
return @{$array_ref} if (ref $array_ref||q{}) eq 'ARRAY';
}
# Return scalar object as one-elem list, if possible...
handler:
for my $context (qw(BOOL STR NUM VALUE SCALAR LAZY)) {
return $crv if exists $attrs->{$context};
}
die _in_context "Can't call $attrs->{sub} in list context";
}
# Handle void context directly...
if (!defined $wantarray) {
handler:
for my $context (qw< VOID DEFAULT >) {
my $handler = $attrs->{$context} or next;
eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
$recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
last;
}
return;
}
# Otherwise, defer evaluation by returning an object...
return $crv;
}
}
for my $context_name (@CONTEXTS, qw< RECOVER _internal_LIST CLEANUP >) {
next if $context_name eq 'LIST' # These
|| $context_name eq 'VOID' # four
|| $context_name eq 'SCALAR' # handled
|| $context_name eq 'NONVOID'; # separately
no strict qw( refs );
*{$context_name} = sub (&;$) {
my ($block, $crv) = @_;
# Ensure we have an object...
my $attrs;
if (!refaddr $crv) {
my $args = do{ package DB; ()=CORE::caller(1); \@DB::args };
my $subname = (CORE::caller(1))[3];
$crv = bless \my $scalar, 'Contextual::Return::Value';
$attrs = $attrs_of{refaddr $crv}
= { args => $args, sub => $subname };
}
else {
$attrs = $attrs_of{refaddr $crv};
}
local $Contextual::Return::__RETOBJ__ = $crv;
# Make sure this block is a possibility too...
if ($context_name ne '_internal_LIST') {
die _in_context "Can't install two $context_name handlers"
if exists $attrs->{$context_name};
$attrs->{$context_name} = $block;
}
# Identify contexts...
my $wantarray = wantarray;
use Want;
$attrs->{want_pure_bool} ||= Want::want('BOOL');
# Prepare for exception handling...
my $recover = $attrs->{RECOVER};
local $Contextual::Return::uplevel = 2;
# Handle list context directly, if possible...
if (wantarray) {
local $Contextual::Return::__RESULT__
= $context_name eq 'RECOVER' ? $Contextual::Return::__RESULT__
: undef
;
# List or ancestral handlers...
handler:
for my $context (qw(LIST VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
my @rv = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [@rv];
}
() = $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
return @rv if !$Contextual::Return::__RESULT__;
return @{$Contextual::Return::__RESULT__};
}
# Convert to list from arrayref handler...
if (my $handler = $attrs->{ARRAYREF}) {
local $Contextual::Return::uplevel = 2;
# Array ref may be returned directly, or via RESULT{}...
my $array_ref = eval { $handler->(@{$attrs->{args}}) };
if ($recover) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$array_ref];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
$array_ref = $Contextual::Return::__RESULT__->[0]
if $Contextual::Return::__RESULT__;
return @{$array_ref} if (ref $array_ref||q{}) eq 'ARRAY';
}
# Return scalar object as one-elem list, if possible...
handler:
for my $context (qw(BOOL STR NUM VALUE SCALAR LAZY)) {
return $crv if exists $attrs->{$context};
}
$@ = _in_context "Can't call $attrs->{sub} in list context";
if ($recover) {
() = $recover->(@{$attrs->{args}});
}
else {
die $@;
}
}
# Handle void context directly...
if (!defined $wantarray) {
handler:
for my $context (qw(VOID DEFAULT)) {
next if !$attrs->{$context};
eval { $attrs->{$context}->(@{$attrs->{args}}) };
if ($recover) {
$recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
last;
}
return;
}
# Otherwise, defer evaluation by returning an object...
return $crv;
}
}
# Alias LAZY to SCALAR...
*LAZY = *SCALAR;
# Set $Data::Dumper::Freezer to 'Contextual::Return::FREEZE' to be able to
# dump contextual return values...
my %operator_impl;
my $no_handler_message = qr{
^ Can't [ ] call [ ] .*? [ ] in [ ] [\w]+ [ ] context
| ^ [\w:]+ [ ] can't [ ] return [ ] a [ ] \w+ [ ] reference
}xms;
sub _flag_self_ref_in {
my ($data_ref, $obj_ref) = @_;
my $type = ref $data_ref;
return if !$type;
for my $value ( $type eq 'SCALAR' ? ${$data_ref} : @{$data_ref} ) {
no warnings 'numeric';
if ($value == $obj_ref) {
$value = '<<<self-reference>>>';
}
}
}
sub FREEZE {
my ($self) = @_;
my $attrs_ref = $attrs_of{refaddr $self};
my $args_ref = $attrs_ref->{args};
my @no_handler;
# Call appropriate operator handler, defusing and recording exceptions...
my $overloaded = sub {
my ($context, $op) = @_;
# Try the operator...
my $retval = eval { $operator_impl{$op}->($self,@{$args_ref}) };
# Detect and report internal exceptions...
if (my $exception = $@) {
if ($exception =~ $no_handler_message) {
push @no_handler, $context;
return ();
}
return { $context => "<<<Throws exception: $exception>>>" };
}
# Detect self-referential overloadings (to avoid infinite recursion)...
{
no warnings 'numeric';
if (ref $retval eq 'REF' && ${$retval} == ${$self}) {
return { $context => "<<<self-reference>>>" };
}
}
# Normal return of contextual value labelled by context...
return { $context => $retval };
};
my @values;
# Where did this value originate?
push @values, { ISA => 'Contextual::Return::Value' };
push @values, { FROM => $attrs_ref->{sub} };
# Does it return a value in void context?
if (exists $attrs_ref->{VOID} || exists $attrs_ref->{DEFAULT}) {
push @values, { VOID => undef };
}
else {
push @no_handler, 'VOID';
}
# Generate list context value by "pretend" LIST handler...
push @values, { LIST => [ _internal_LIST(sub{}, $self) ] };
_flag_self_ref_in($values[-1]{LIST}, $self);
# Generate scalar context values by calling appropriate handler...
push @values, $overloaded->( STR => q{""} );
push @values, $overloaded->( NUM => '0+' );
push @values, $overloaded->( BOOL => 'bool' );
push @values, $overloaded->( SCALARREF => '${}' );
_flag_self_ref_in($values[-1]{SCALARREF}, $self);
push @values, $overloaded->( ARRAYREF => '@{}' );
_flag_self_ref_in($values[-1]{ARRAYREF}, $self);
push @values, $overloaded->( CODEREF => '&{}' );
push @values, $overloaded->( HASHREF => '%{}' );
push @values, $overloaded->( GLOBREF => '*{}' );
# Are there handlers for various "generic" super-contexts...
my @fallbacks = grep { $attrs_ref->{$_} }
qw< DEFAULT NONVOID SCALAR VALUE REF RECOVER >;
push @values, { NO_HANDLER => \@no_handler };
push @values, { FALLBACKS => \@fallbacks };
# Temporarily replace object being dumped, by values found...
$_[0] = \@values;
}
# Call this method on a contextual return value object to debug it...
sub DUMP {
if (require Data::Dumper) {
my ($crv) = @_;
FREEZE($crv);
return Data::Dumper::Dumper($crv);
}
else {
Carp::carp("Can't DUMP contextual return value (no Data::Dumper!)");
return;
}
}
package Contextual::Return::Value;
BEGIN { *_in_context = *Contextual::Return::_in_context; }
use Scalar::Util qw( refaddr );
BEGIN {
%operator_impl = (
q{""} => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(STR SCALAR LAZY VALUE NONVOID DEFAULT NUM)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "Can't call $attrs->{sub} in string context";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
q{0+} => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(NUM SCALAR LAZY VALUE NONVOID DEFAULT STR)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "Can't call $attrs->{sub} in numeric context";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
q{bool} => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
# Handle Calls in Pure Boolean context...
my @PUREBOOL = $attrs->{want_pure_bool} ? ('PUREBOOL') : ();
$attrs->{want_pure_bool} = 0;
handler:
for my $context (@PUREBOOL, qw(BOOL SCALAR LAZY VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $outer_sig_warn = $SIG{__WARN__};
local $SIG{__WARN__}
= sub{ return if $_[0] =~ /^Exiting \S+ via next/;
goto &{$outer_sig_warn} if $outer_sig_warn;
warn @_;
};
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "Can't call $attrs->{sub} in boolean context";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
'${}' => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(SCALARREF REF NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
# Catch bad behaviour...
die _in_context "$context block did not return ",
"a suitable reference to the scalar dereference"
if ref($rv) ne 'SCALAR' && ref($rv) ne 'OBJ';
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
if ( $attrs->{FIXED} ) {
$_[0] = \$self;
}
return \$self;
},
'@{}' => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
local $Contextual::Return::__RESULT__;
handler:
for my $context (qw(ARRAYREF REF)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
# Catch bad behaviour...
die _in_context "$context block did not return ",
"a suitable reference to the array dereference"
if ref($rv) ne 'ARRAY' && ref($rv) ne 'OBJ';
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
handler:
for my $context (qw(LIST VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::uplevel = 2;
my @rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [@rv];
}
() = $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
@rv = @{$Contextual::Return::__RESULT__->[0]};
}
if ( $attrs->{FIXED} ) {
$_[0] = \@rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { @rv };
}
return \@rv;
}
return [ $self ];
},
'%{}' => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(HASHREF REF NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
# Catch bad behaviour...
die _in_context "$context block did not return ",
"a suitable reference to the hash dereference"
if ref($rv) ne 'HASH' && ref($rv) ne 'OBJ';
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "$attrs->{sub} can't return a hash reference";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
'&{}' => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(CODEREF REF NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
# Catch bad behaviour...
die _in_context "$context block did not return ",
"a suitable reference to the subroutine dereference"
if ref($rv) ne 'CODE' && ref($rv) ne 'OBJ';
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "$attrs->{sub} can't return a subroutine reference";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
'*{}' => sub {
my ($self) = @_;
local $Contextual::Return::__RETOBJ__ = $self;
my $attrs = $attrs_of{refaddr $self};
handler:
for my $context (qw(GLOBREF REF NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $rv = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$rv];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$rv = $Contextual::Return::__RESULT__->[0];
}
# Catch bad behaviour...
die _in_context "$context block did not return ",
"a suitable reference to the typeglob dereference"
if ref($rv) ne 'GLOB' && ref($rv) ne 'OBJ';
if ( $attrs->{FIXED} ) {
$_[0] = $rv;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $rv };
}
return $rv;
}
$@ = _in_context "$attrs->{sub} can't return a typeglob reference";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
},
);
}
use overload %operator_impl, fallback => 1;
sub DESTROY {
my ($id) = refaddr shift;
my $attrs = $attrs_of{$id};
if (my $handler = $attrs->{CLEANUP}) {
$handler->(@{ $attrs->{args} });
}
delete $attrs_of{$id};
return;
}
my $NO_SUCH_METHOD = qr/\ACan't (?:locate|call)(?: class| object)? method/ms;
# Forward metainformation requests to actual class...
sub can {
my ($invocant) = @_;
# Only forward requests on actual C::R::V objects...
if (ref $invocant) {
our $AUTOLOAD = 'can';
goto &AUTOLOAD;
}
# Refer requests on classes to actual class hierarchy...
return $invocant->SUPER::can(@_[1..$#_]);
}
sub isa {
# Only forward requests on actual C::R::V objects...
my ($invocant) = @_;
if (ref $invocant) {
our $AUTOLOAD = 'isa';
goto &AUTOLOAD;
}
# Refer requests on classes to actual class hierarchy...
return $invocant->SUPER::isa(@_[1..$#_]);
}
sub AUTOLOAD {
my ($self) = @_;
our $AUTOLOAD;
my ($requested_method) = $AUTOLOAD =~ m{ .* :: (.*) }xms ? $1 : $AUTOLOAD;
my $attrs = $attrs_of{refaddr $self} || {};
local $Contextual::Return::__RETOBJ__ = $self;
# First, see if there is a method call handler...
if (my $context_handler = $attrs->{METHOD}) {
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my @method_handlers = eval { $context_handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [\@method_handlers];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
@method_handlers = @{$Contextual::Return::__RESULT__};
}
# Locate the correct method handler (if any)...
MATCHER:
while (my ($matcher, $method_handler) = splice @method_handlers, 0, 2) {
if (ref($matcher) eq 'ARRAY') {
next MATCHER
if !grep { $requested_method =~ $_ } @{$matcher};
}
elsif ($requested_method !~ $matcher) {
next MATCHER;
}
shift;
if (wantarray) {
my @result = eval {
local $_ = $requested_method;
$method_handler->(@_);
};
die _in_context $@ if $@;
return @result;
}
else {
my $result = eval {
local $_ = $requested_method;
$method_handler->(@_);
};
die _in_context $@ if $@;
return $result;
}
}
}
# Next, try to create an object on which to call the method...
handler:
for my $context (qw(OBJREF STR SCALAR LAZY VALUE NONVOID DEFAULT)) {
my $handler = $attrs->{$context} or next;
local $Contextual::Return::__RESULT__;
local $Contextual::Return::uplevel = 2;
my $object = eval { $handler->(@{$attrs->{args}}) };
if (my $recover = $attrs->{RECOVER}) {
if (!$Contextual::Return::__RESULT__) {
$Contextual::Return::__RESULT__ = [$object];
}
scalar $recover->(@{$attrs->{args}});
}
elsif ($@) {
die $@;
}
if ($Contextual::Return::__RESULT__) {
$object = $Contextual::Return::__RESULT__->[0];
}
if ( $attrs->{FIXED} ) {
$_[0] = $object;
}
elsif ( !$attrs->{ACTIVE} ) {
$attrs->{$context} = sub { $object };
}
shift;
if (wantarray) {
my @result = eval { $object->$requested_method(@_) };
my $exception = $@;
return @result if !$exception;
die _in_context $exception if $exception !~ $NO_SUCH_METHOD;
}
else {
my $result = eval { $object->$requested_method(@_) };
my $exception = $@;
return $result if !$exception;
die _in_context $exception if $exception !~ $NO_SUCH_METHOD;
}
$@ = _in_context "Can't call method '$requested_method' on $context value returned by $attrs->{sub}";
if (my $recover = $attrs->{RECOVER}) {
scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
}
# Otherwise, the method cannot be called, so react accordingly...
$@ = _in_context "Can't call method '$requested_method' on value returned by $attrs->{sub}";
if (my $recover = $attrs->{RECOVER}) {
return scalar $recover->(@{$attrs->{args}});
}
else {
die $@;
}
}
package Contextual::Return::Lvalue;
sub TIESCALAR {
my ($package, @handler) = @_;
return bless {@handler}, $package;
}
# Handle calls that are lvalues...
sub STORE {
local *CALLER::_ = \$_;
local *_ = \$_[1];
local $Contextual::Return::uplevel = 1;
local $Contextual::Return::__RESULT__;
my $rv = $_[0]{LVALUE}( @{$_[0]{args}} );
return $rv if !$Contextual::Return::__RESULT__;
return $Contextual::Return::__RESULT__->[0];
}
# Handle calls that are rvalues...
sub FETCH {
local $Contextual::Return::uplevel = 1;
local $Contextual::Return::__RESULT__;
my $rv = $_[0]{RVALUE} ? $_[0]{RVALUE}( @{$_[0]{args}} ) : undef;
return $rv if !$Contextual::Return::__RESULT__;
return $Contextual::Return::__RESULT__->[0];
}
sub DESTROY {};
1; # Magic true value required at end of module
__END__
=head1 NAME
Contextual::Return - Create context-senstive return values
=head1 VERSION
This document describes Contextual::Return version 0.003001
=head1 SYNOPSIS
use Contextual::Return;
use Carp;
sub foo {
return
SCALAR { 'thirty-twelve' }
LIST { 1,2,3 }
BOOL { 1 }
NUM { 7*6 }
STR { 'forty-two' }
HASHREF { {name => 'foo', value => 99} }
ARRAYREF { [3,2,1] }
GLOBREF { \*STDOUT }
CODEREF { croak "Don't use this result as code!"; }
;
}
# and later...
if (my $foo = foo()) {
for my $count (1..$foo) {
print "$count: $foo is:\n"
. " array: @{$foo}\n"
. " hash: $foo->{name} => $foo->{value}\n"
;
}
print {$foo} $foo->();
}
=head1 DESCRIPTION
Usually, when you need to create a subroutine that returns different values in
different contexts (list, scalar, or void), you write something like:
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data,
# depending on call context...
if (wantarray()) {
return @server_data{ qw(name uptime load users) };
}
if (defined wantarray()) {
return $server_data{load};
}
if (!defined wantarray()) {
carp 'Useless use of get_server_status() in void context';
return;
}
else {
croak q{Bad context! No biscuit!};
}
}
That works okay, but the code could certainly be more readable. In
its simplest usage, this module makes that code more readable by
providing three subroutines--C<LIST()>, C<SCALAR()>, C<VOID()>--that
are true only when the current subroutine is called in the
corresponding context:
use Contextual::Return;
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data
# depending on call context...
if (LIST) { return @server_data{ qw(name uptime load users) } }
if (SCALAR) { return $server_data{load} }
if (VOID) { print "$server_data{load}\n" }
else { croak q{Bad context! No biscuit!} }
}
=head2 Contextual returns
Those three subroutines can also be used in another way: as labels on a
series of I<contextual return blocks> (collectively known as a I<contextual
return sequence>). When a context sequence is returned, it automatically
selects the appropriate contextual return block for the calling context.
So the previous example could be written even more cleanly as:
use Contextual::Return;
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data
# depending on call context...
return (
LIST { return @server_data{ qw(name uptime load users) } }
SCALAR { return $server_data{load} }
VOID { print "$server_data{load}\n" }
DEFAULT { croak q{Bad context! No biscuit!} }
);
}
The context sequence automatically selects the appropriate block for each call
context.
=head2 Lazy contextual return values
C<LIST> and C<VOID> blocks are always executed during the C<return>
statement. However, scalar return blocks (C<SCALAR>, C<STR>, C<NUM>,
C<BOOL>, etc.) blocks are not. Instead, returning any of scalar block
types causes the subroutine to return an object that lazily
evaluates that block only when the return value is used.
This means that returning a C<SCALAR> block is a convenient way to
implement a subroutine with a lazy return value. For example:
sub digest {
return SCALAR {
my ($text) = @_;
md5($text);
}
}
my $digest = digest($text);
print $digest; # md5() called only when $digest used as string
To better document this usage, the C<SCALAR> block has a synonym: C<LAZY>.
sub digest {
return LAZY {
my ($text) = @_;
md5($text);
}
}
=head2 Active contextual return values
Once a return value has been lazily evaluated in a given context,
the resulting value is cached, and thereafter reused in that same context.
However, you can specify that, rather than being cached, the value
should be re-evaluated I<every> time the value is used:
sub make_counter {
my $counter = 0;
return ACTIVE
SCALAR { ++$counter }
ARRAYREF { [1..$counter] }
}
my $idx = make_counter();
print "$idx\n"; # 1
print "$idx\n"; # 2
print "[@$idx]\n"; # [1 2]
print "$idx\n"; # 3
print "[@$idx]\n"; # [1 2 3]
=head2 Semi-lazy contextual return values
Sometimes, single or repeated lazy evaluation of a scalar return value
in different contexts isn't what you really want. Sometimes what you
really want is for the return value to be lazily evaluated once only (the
first time it's used in any context), and then for that first value to
be reused whenever the return value is subsequently reevaluated in any
other context.
To get that behaviour, you can use the C<FIXED> modifier, which causes
the return value to morph itself into the actual value the first time it
is used. For example:
sub lazy {
return
SCALAR { 42 }
ARRAYREF { [ 1, 2, 3 ] }
;
}
my $lazy = lazy();
print $lazy + 1; # 43
print "@{$lazy}"; # 1 2 3
sub semilazy {
return FIXED
SCALAR { 42 }
ARRAYREF { [ 1, 2, 3 ] }
;
}
my $semi = semilazy();
print $semi + 1; # 43
print "@{$semi}"; # die q{Can't use string ("42") as an ARRAY ref}
=head2 Finer distinctions of scalar context
Because the scalar values returned from a context sequence are lazily
evaluated, it becomes possible to be more specific about I<what kind> of
scalar value should be returned: a boolean, a number, or a string. To support
those distinctions, Contextual::Return provides four extra context blocks:
C<NUM>, C<STR>, C<BOOL>, and C<PUREBOOL>:
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data
# depending on call context...
return (
LIST { @server_data{ qw(name uptime load users) } }
PUREBOOL { $_ = $server_data{uptime}; $server_data{uptime} > 0 }
BOOL { $server_data{uptime} > 0 }
NUM { $server_data{load} }
STR { "$server_data{name}: $server_data{uptime}" }
VOID { print "$server_data{load}\n" }
DEFAULT { croak q{Bad context! No biscuit!} }
);
}
With these in place, the object returned from a scalar-context call to
C<get_server_status()> now behaves differently, depending on how
it's used. For example:
if ( my $status = get_server_status() ) { # BOOL: True if uptime > 0
$load_distribution[$status]++; # INT: Evaluates to load value
print "$status\n"; # STR: Prints "name: uptime"
}
if (get_server_status()) { # PUREBOOL: also sets $_;
print; # ...which is then used here
}
=head3 Boolean vs Pure Boolean contexts
There is a special subset of boolean contexts where the return value is being
used and immediately thrown away. For example, in the loop:
while (get_data()) {
...
}
the value returned by C<get_data()> is tested for truth and then discarded.
This is known as "pure boolean context". In contrast, in the loop:
while (my $data = get_data()) {
...
}
the value returned by C<get_data()> is first assigned to C<$data>, then
tested for truth. Because of the assignment, the return value is I<not>
discarded after the boolean test. This is ordinary "boolean context".
In Perl, pure boolean context is often associated with a special side-effect,
that does not occur in regular boolean contexts. For example:
while (<>) {...} # $_ set as side-effect of pure boolean context
while ($v = <>) {...} # $_ NOT set in ordinary boolean context
Contextual::Return supports this with a special subcase of C<BOOL> named
<PUREBOOL>. In pure boolean contexts, Contextual::Return will call a
C<PUREBOOL> handler if one has been defined, or fall back to a C<BOOL>
or C<SCALAR> handler if no C<PUREBOOL> handler exists. In ordinary
boolean contexts only the C<BOOL> or C<SCALAR> handlers are tried, even
if a C<PUREBOOL> handler is also defined.
Typically C<PUREBOOL> handlers are set up to have some side-effect (most
commonly: setting C<$_> or <$@>), like so:
sub get_data {
my ($succeeded, @data) = _go_and_get_data();
return
PUREBOOL { $_ = $data[0]; $succeeded; }
BOOL { $succeeded; }
SCALAR { $data[0]; }
LIST { @data; }
}
However, there is no requirement that they have side-effects. For example,
they can also be used to implement "look-but-don't-retrieve-yet" checking:
sub get_data {
my $data;
return
PUREBOOL { _check_for_but_dont_get_data(); }
BOOL { defined( $data ||= _go_and_get_data() ); }
REF { $data ||= _go_and_get_data(); }
}
=head2 Self-reference within handlers
Any handler can refer to the contextual return object it is part of, by
calling the C<RETOBJ()> function. This is particularly useful for C<PUREBOOL>
and C<LIST> handlers. For example:
return
PUREBOOL { $_ = RETOBJ; next handler; }
BOOL { !$failed; }
DEFAULT { $data; };
=head2 Referential contexts
The other major kind of scalar return value is a reference.
Contextual::Return provides contextual return blocks that allow you to
specify what to (lazily) return when the return value of a subroutine is
used as a reference to a scalar (C<SCALARREF {...}>), to an array
(C<ARRAYREF {...}>), to a hash (C<HASHREF {...}>), to a subroutine
(C<CODEREF {...}>), or to a typeglob (C<GLOBREF {...}>).
For example, the server status subroutine shown earlier could be extended to
allow it to return a hash reference, thereby supporting "named return values":
sub get_server_status {
my ($server_ID) = @_;
# Acquire server data somehow...
my %server_data = _ascertain_server_status($server_ID);
# Return different components of that data
# depending on call context...
return (
LIST { @server_data{ qw(name uptime load users) } }
BOOL { $server_data{uptime} > 0 }
NUM { $server_data{load} }
STR { "$server_data{name}: $server_data{uptime}" }
VOID { print "$server_data{load}\n" }
HASHREF { return \%server_data }
DEFAULT { croak q{Bad context! No biscuit!} }
);
}
# and later...
my $users = get_server_status->{users};
# or, lazily...
my $server = get_server_status();
print "$server->{name} load = $server->{load}\n";
=head2 Interpolative referential contexts
The C<SCALARREF {...}> and C<ARRAYREF {...}> context blocks are
especially useful when you need to interpolate a subroutine into
strings. For example, if you have a subroutine like:
sub get_todo_tasks {
return (
SCALAR { scalar @todo_list } # How many?
LIST { @todo_list } # What are they?
);
}
# and later...
print "There are ", scalar(get_todo_tasks()), " tasks:\n",
get_todo_tasks();
then you could make it much easier to interpolate calls to that
subroutine by adding:
sub get_todo_tasks {
return (
SCALAR { scalar @todo_list } # How many?
LIST { @todo_list } # What are they?
SCALARREF { \scalar @todo_list } # Ref to how many
ARRAYREF { \@todo_list } # Ref to them
);
}
# and then...
print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
In fact, this behaviour is so useful that it's the default. If you
don't provide an explicit C<SCALARREF {...}> block,
Contextual::Return automatically provides an implicit one that simply
returns a reference to whatever would have been returned in scalar context.
Likewise, if no C<ARRAYREF {...}> block is specified, the module supplies one
that returns the list-context return value wrapped up in an array reference.
So you could just write:
sub get_todo_tasks {
return (
SCALAR { scalar @todo_list } # How many?
LIST { @todo_list } # What are they?
);
}
# and still do this...
print "There are ${get_todo_tasks()} tasks:\n@{get_todo_tasks()}";
=head2 Fallback contexts
As the previous sections imply, the C<BOOL {...}>, C<NUM {...}>, C<STR
{...}>, and various C<*REF {...}> blocks, are special cases of the
general C<SCALAR {...}> context block. If a subroutine is called in one
of these specialized contexts but does not use the corresponding context
block, then the more general C<SCALAR {...}> block is used instead (if
it has been specified).
So, for example:
sub read_value_from {
my ($fh) = @_;
my $value = <$fh>;
chomp $value;
return (
BOOL { defined $value }
SCALAR { $value }
);
}
ensures that the C<read_value_from()> subroutine returns true in boolean
contexts if the read was successful. But, because no specific C<NUM {...}>
or C<STR {...}> return behaviours were specified, the subroutine falls back on
using its generic C<SCALAR {...}> block in all other scalar contexts.
Another way to think about this behaviour is that the various kinds of
scalar context blocks form a hierarchy:
SCALAR
^
|
|--< BOOL
|
|--< NUM
|
`--< STR
Contextual::Return uses this hierarchical relationship to choose the most
specific context block available to handle any particular return context,
working its way up the tree from the specific type it needs, to the more
general type, if that's all that is available.
There are two slight complications to this picture. The first is that Perl
treats strings and numbers as interconvertable so the diagram (and the
Contextual::Return module) also has to allow these interconversions as a
fallback strategy:
SCALAR
^
|
|--< BOOL
|
|--< NUM
| : ^
| v :
`--< STR
The dotted lines are meant to indicate that this intraconversion is secondary
to the main hierarchical fallback. That is, in a numeric context, a C<STR
{...}> block will only be used if there is no C<NUM {...}> block I<and> no
C<SCALAR {...}> block. In other words, the generic context type is always
used in preference to string<->number conversion.
The second slight complication is that the above diagram only shows a
small part of the complete hierarchy of contexts supported by
Contextual::Return. The full fallback hierarchy (including dotted
interconversions) is:
DEFAULT
^
|
|--< VOID
|
`--< NONVOID
^
|
|--< VALUE <...............
| ^ :
| | :
| |--< SCALAR <.......:...
| | ^ :
| | | :
| | |--< BOOL :
| | | ^ :
| | | | :
| | | PUREBOOL :
| | | :
| | |--< NUM <..:.
| | | : ^ :
| | | v : :
| | `--< STR <....:..
| | :
| | ::
| `--< LIST ................: :
| : ^ :
| : : :
`--- REF : : :
^ : : :
| v : :
|--< ARRAYREF :
| :
|--< SCALARREF .............:
|
|--< HASHREF
|
|--< CODEREF
|
|--< GLOBREF
|
`--< OBJREF <....... METHOD
As before, each dashed arrow represents a fallback relationship. That
is, if the required context specifier isn't available, the arrows are
followed until a more generic one is found. The dotted arrows again
represent the interconversion of return values, which is
attempted only after the normal hierarchical fallback fails.
For example, if a subroutine is called in a context that expects a
scalar reference, but no C<SCALARREF {...}> block is provided, then
Contextual::Return tries the following blocks in order:
REF {...}
NONVOID {...}
DEFAULT {...}
STR {...} (automatically taking a reference to the result)
NUM {...} (automatically taking a reference to the result)
SCALAR {...} (automatically taking a reference to the result)
VALUE {...} (automatically taking a reference to the result)
Likewise, in a list context, if there is no C<LIST {...}> context block, the
module tries:
VALUE {...}
NONVOID {...}
DEFAULT {...}
ARRAYREF {...} (automatically dereferencing the result)
STR {...} (treating it as a list of one element)
NUM {...} (treating it as a list of one element)
SCALAR {...} (treating it as a list of one element)
The more generic context blocks are especially useful for intercepting
unexpected and undesirable call contexts. For example, to turn I<off>
the automatic scalar-ref and array-ref interpolative behaviour described
in L<Interpolative referential contexts>, you could intercept I<all>
referential contexts using a generic C<REF {...}> context block:
sub get_todo_tasks {
return (
SCALAR { scalar @todo_list } # How many?
LIST { @todo_list } # What are they?
REF { croak q{get_todo_task() can't be used as a reference} }
);
}
print 'There are ', get_todo_tasks(), '...'; # Still okay
print "There are ${get_todo_tasks()}..."; # Throws an exception
=head2 Treating returns values as objects
Normally, when a return value is treated as an object (i.e. has a method
called on it), Contextual::Return invokes any C<OBJREF> handler that was
specified in the contextual return list, and delegates the method call to
the object returned by that handler.
However, you can also be more specific, by specifying a C<METHOD> context
handler in the contextual return list. The block of this handler is expected
to return one or more method-name/method-handler pairs, like so:
return
METHOD {
get_count => sub { my $n = shift; $data[$n]{count} },
get_items => sub { my $n = shift; $data[$n]{items} },
clear => sub { @data = (); },
reset => sub { @data = (); },
}
Then, whenever one of the specified methods is called on the return value,
the corresponding subroutine will be called to implement it.
The method handlers must always be subroutine references, but the method-name
specifiers may be strings (as in the previous example) or they may be
specified generically, as either regexes or array references. Generic method
names are used to call the same handler for two or more distinct method names.
For example, the previous example could be simplified to:
return
METHOD {
qr/get_(\w+)/ => sub { my $n = shift; $data[$n]{$1} },
['clear','reset'] => sub { @data = (); },
}
A method name specified by regex will invoke the corresponding handler for any
method call request that the regex matches. A method name specified by array
ref will invoke the corresponding handler if the method requested matches any
of the elements of the array (which may themselves be strings or regexes).
When the method handler is invoked, the name of the method requested is
passed to the handler in C<$_>, and the method's argument list is passed
(as usual) via C<@_>.
Note that any methods not explicitly handled by the C<METHOD> handlers
will still be delegated to the object returned by the C<OBJREF> handler
(if it is also specified).
=head2 Deferring handlers
Because the various handlers form a hierarchy, it's possible to
implement more specific handlers by falling back on ("deferring to")
more general ones. For example, L<a C<PUREBOOL> handler|"Boolean vs Pure
Boolean contexts"> is almost always identical in its basic behaviour to
the corresponding C<BOOL> handler, except that it adds some side-effect.
For example:
return
PUREBOOL { $_ = $return_val; defined $return_val && $return_val > 0 }
BOOL { defined $return_val && $return_val > 0 }
SCALAR { $return_val; }
So Contextual::Return allows you to have a handler perform some action
and then defer to a more general handler to supply the actual return
value. To fall back to a more general case in this way, you simply write:
next handler;
at the end of the handler in question, after which Contextual::Return
will find the next-most-specific handler and execute it as well. So the
previous example, could be re-written:
return
PUREBOOL { $_ = $return_val; next handler; }
BOOL { defined $return_val && $return_val > 0 }
SCALAR { $return_val; }
Note that I<any> specific handler can defer to a more general one in
this same way. For example, you could provide consistent and
maintainable type-checking for a subroutine that returns references by
providing C<ARRAYREF>, C<HASHREF>, and C<SCALARREF> handlers that all
defer to a generic C<REF> handler, like so:
my $retval = _get_ref();
return
SCALARREF { croak 'Type mismatch' if ref($retval) ne 'SCALAR';
next handler;
}
ARRAYREF { croak 'Type mismatch' if ref($retval) ne 'ARRAY';
next handler;
}
HASHREF { croak 'Type mismatch' if ref($retval) ne 'HASH';
next handler;
}
REF { $retval }
If, at a later time, the process of returning a reference became more complex,
only the C<REF> handler would have to be updated.
=head2 Nested handlers
Another way of factoring out return behaviour is to nest more specific
handlers inside more general ones. For instance, in the final example given in
L<"Boolean vs Pure Boolean contexts">:
sub get_data {
my $data;
return
PUREBOOL { _check_for_but_dont_get_data(); }
BOOL { defined( $data ||= _go_and_get_data() ); }
REF { $data ||= _go_and_get_data(); }
}
you could factor out the repeated calls to C<_go_and_get_data()> like so:
sub get_data {
return
PUREBOOL { _check_for_but_dont_get_data(); }
DEFAULT {
my $data = _go_and_get_data();
BOOL { defined $data; }
REF { $data; }
}
}
Here, the C<DEFAULT> handler deals with every return context except pure
boolean. Within that C<DEFAULT> handler, the data is first retrieved,
and then two "sub-handlers" deal with the ordinary boolean and
referential contexts.
Typically nested handlers are used in precisely this way: to optimize
for inexpensive special cases (such as pure boolean or integer or void
return contexts) and only do extra work for those other cases that
require it.
=head2 Failure contexts
Two of the most common ways to specify that a subroutine has failed
are to return a false value, or to throw an exception. The
Contextual::Return module provides a mechanism that allows the
subroutine writer to support I<both> of these mechanisms at the
same time, by using the C<FAIL> specifier.
A return statement of the form:
return FAIL;
causes the surrounding subroutine to return C<undef> (i.e. false) in
boolean contexts, and to throw an exception in any other context. For example:
use Contextual::Return;
sub get_next_val {
my $next_val = <>;
return FAIL if !defined $next_val;
chomp $next_val;
return $next_val;
}
If the C<return FAIL> statement is executed, it will either return false in a
boolean context:
if (my $val = get_next_val()) { # returns undef if no next val
print "[$val]\n";
}
or else throw an exception if the return value is used in any
other context:
print get_next_val(); # throws exception if no next val
my $next_val = get_next_val();
print "[$next_val]\n"; # throws exception if no next val
The exception that is thrown is of the form:
Call to main::get_next_val() failed at demo.pl line 42
but you can change that message by providing a block to the C<FAIL>, like so:
return FAIL { "No more data" } if !defined $next_val;
in which case, the final value of the block becomes the exception message:
No more data at demo.pl line 42
=head2 Configurable failure contexts
The default C<FAIL> behaviour--false in boolean context, fatal in all
others--works well in most situations, but violates the Platinum Rule ("Do
unto others as I<they> would have done unto them").
So it may be user-friendlier if the user of a module is allowed decide how
the module's subroutines should behave on failure. For example, one user
might prefer that failing subs always return undef; another might prefer
that they always throw an exception; a third might prefer that they
always log the problem and return a special Failure object; whilst a
fourth user might want to get back C<0> in scalar contexts, an empty list
in list contexts, and an exception everywhere else.
You could create a module that allows the user to specify all these
alternatives, like so:
package MyModule;
use Contextual::Return;
use Log::StdLog;
sub import {
my ($package, @args) = @_;
Contextual::Return::FAIL_WITH {
':false' => sub { return undef },
':fatal' => sub { croak @_ },
':filed' => sub {
print STDLOG 'Sub ', (caller 1)[3], ' failed';
return Failure->new();
},
':fussy' => sub {
SCALAR { undef }
LIST { () }
DEFAULT { croak @_ }
},
}, @args;
}
This configures Contextual::Return so that, instead of the usual
false-or-fatal semantics, every C<return FAIL> within MyModule's namespace is
implemented by one of the four subroutines specified in the hash that was
passed to C<FAIL_WITH>.
Which of those four subs implements the C<FAIL> is determined by the
arguments passed after the hash (i.e. by the contents of C<@args>).
C<FAIL_WITH> walks through that list of arguments and compares
them against the keys of the hash. If a key matches an argument, the
corresponding value is used as the implementation of C<FAIL>. Note that,
if subsequent arguments also match a key, their subroutine overrides the
previously installed implementation, so only the final override has any
effect. Contextual::Return generates warnings when multiple overrides are
specified.
All of which mean that, if a user loaded the MyModule module like this:
use MyModule qw( :fatal other args here );
then every C<FAIL> within MyModule would be reconfigured to throw an exception
in all circumstances, since the presence of the C<':fatal'> in the argument
list will cause C<FAIL_WITH> to select the hash entry whose key is C<':fatal'>.
On the other hand, if they loaded the module:
use MyModule qw( :fussy other args here );
then each C<FAIL> within MyModule would return undef or empty list or throw an
exception, depending on context, since that's what the subroutine whose key is
C<':fussy'> does.
Many people prefer module interfaces with a C<< I<flag> => I<value> >>
format, and C<FAIL_WITH> supports this too. For example, if you
wanted your module to take a C<-fail> flag, whose associated value could
be any of C<"undefined">, C<"exception">, C<"logged">, or C<"context">,
then you could implement that simply by specifying the flag as the first
argument (i.e. I<before> the hash) like so:
sub import {
my $package = shift;
Contextual::Return::FAIL_WITH -fail => {
'undefined' => sub { return undef },
'exception' => sub { croak @_ },
'logged' => sub {
print STDLOG 'Sub ', (caller 1)[3], ' failed';
return Failure->new();
},
'context' => sub {
SCALAR { undef }
LIST { () }
DEFAULT { croak @_ }
},
}, @_;
and then load the module:
use MyModule qw( other args here ), -fail=>'undefined';
or:
use MyModule qw( other args here ), -fail=>'exception';
In this case, C<FAIL_WITH> scans the argument list for a pair of values: its
flag string, followed by some other selector value. Then it looks up the
selector value in the hash, and installs the corresponding subroutine as its
local C<FAIL> handler.
If this "flagged" interface is used, the user of the module can also
specify their own handler directly, by passing a subroutine reference as
the selector value instead of a string:
use MyModule qw( other args here ), -fail=>sub{ die 'horribly'};
If this last example were used, any call to C<FAIL> within MyModule
would invoke the specified anonymous subroutine (and hence throw a
'horribly' exception).
Note that, any overriding of a C<FAIL> handler is specific to the
namespace and file from which the subroutine that calls C<FAIL_WITH> is
itself called. Since C<FAIL_WITH> is designed to be called from within a
module's C<import()> subroutine, that generally means that the C<FAIL>s
within a given module X are only overridden for the current namespace
within the particular file from module X is loaded. This means that two
separate pieces of code (in separate files or separate namespaces) can
each independently overide a module's C<FAIL> behaviour, without
interfering with each other.
=head2 Lvalue contexts
Recent versions of Perl offer (limited) support for lvalue subroutines:
subroutines that return a modifiable variable, rather than a simple constant
value.
Contextual::Return can make it easier to create such subroutines, within the
limitations imposed by Perl itself. The limitations that Perl places on lvalue
subs are:
=over
=item 1.
The subroutine must be declared with an C<:lvalue> attribute:
sub foo :lvalue {...}
=item 2.
The subroutine must not return via an explicit C<return>. Instead, the
last statement must evaluate to a variable, or must be a call to another
lvalue subroutine call.
my ($foo, $baz);
sub foo :lvalue {
$foo; # last statement evals to a var
}
sub bar :lvalue {
foo(); # last statement is lvalue sub call
}
sub baz :lvalue {
my ($arg) = @_;
$arg > 0 # last statement evals...
? $baz # ...to a var
: bar(); # ...or to an lvalue sub call
}
=back
Thereafter, any call to the lvalue subroutine produces a result that can be
assigned to:
baz(0) = 42; # same as: $baz = 42
baz(1) = 84; # same as: bar() = 84
# which is the same as: foo() = 84
# which is the same as: $foo = 84
Ultimately, every lvalue subroutine must return a scalar variable, which
is then used as the lvalue of the assignment (or whatever other lvalue
operation is applied to the subroutine call). Unfortunately, because the
subroutine has to return this variable I<before> the assignment
can take place, there is no way that a normal lvalue subroutine can
get access to the value that will eventually be assigned to its
return value.
This is occasionally annoying, so the Contextual::Return module offers
a solution: in addition to all the context blocks described above, it
provides three special contextual return blocks specifically for use in
lvalue subroutines: C<LVALUE>, C<RVALUE>, and C<NVALUE>.
Using these blocks you can specify what happens when an lvalue
subroutine is used in lvalue and non-lvalue (rvalue) context. For
example:
my $verbosity_level = 1;
# Verbosity values must be between 0 and 5...
sub verbosity :lvalue {
LVALUE { $verbosity_level = max(0, min($_, 5)) }
RVALUE { $verbosity_level }
}
The C<LVALUE> block is executed whenever C<verbosity> is called as an lvalue:
verbosity() = 7;
The block has access to the value being assigned, which is passed to it
as C<$_>. So, in the above example, the assigned value of 7 would be
aliased to C<$_> within the C<LVALUE> block, would be reduced to 5 by the
"min-of-max" expression, and then assigned to C<$verbosity_level>.
(If you need to access the caller's C<$_>, it's also still available:
as C<$CALLER::_>.)
When the subroutine isn't used as an lvalue:
print verbosity();
the C<RVALUE> block is executed instead and its final value returned.
Within an C<RVALUE> block you can use any of the other features of
Contextual::Return. For example:
sub verbosity :lvalue {
LVALUE { $verbosity_level = int max(0, min($_, 5)) }
RVALUE {
NUM { $verbosity_level }
STR { $description[$verbosity_level] }
BOOL { $verbosity_level > 2 }
}
}
but the context sequence must be nested inside an C<RVALUE> block.
You can also specify what an lvalue subroutine should do when it is used
neither as an lvalue nor as an rvalue (i.e. in void context), by using an
C<NVALUE> block:
sub verbosity :lvalue {
my ($level) = @_;
NVALUE { $verbosity_level = int max(0, min($level, 5)) }
LVALUE { $verbosity_level = int max(0, min($_, 5)) }
RVALUE {
NUM { $verbosity_level }
STR { $description[$verbosity_level] }
BOOL { $verbosity_level > 2 }
}
}
In this example, a call to C<verbosity()> in void context sets the verbosity
level to whatever argument is passed to the subroutine:
verbosity(1);
Note that you I<cannot> get the same effect by nesting a C<VOID> block
within an C<RVALUE> block:
LVALUE { $verbosity_level = int max(0, min($_, 5)) }
RVALUE {
NUM { $verbosity_level }
STR { $description[$verbosity_level] }
BOOL { $verbosity_level > 2 }
VOID { $verbosity_level = $level } # Wrong!
}
That's because, in a void context the return value is never evaluated,
so it is never treated as an rvalue, which means the C<RVALUE> block
never executes.
=head2 Result blocks
Occasionally, it's convenient to calculate a return value I<before> the
end of a contextual return block. For example, you may need to clean up
external resources involved in the calculation after it's complete.
Typically, this requirement produces a slightly awkward code sequence
like this:
return
VALUE {
$db->start_work();
my $result = $db->retrieve_query($query);
$db->commit();
$result;
}
Such code sequences become considerably more awkward when you want
the return value to be context sensitive, in which case you have to
write either:
return
LIST {
$db->start_work();
my @result = $db->retrieve_query($query);
$db->commit();
@result;
}
SCALAR {
$db->start_work();
my $result = $db->retrieve_query($query);
$db->commit();
$result;
}
or, worse:
return
VALUE {
$db->start_work();
my $result = LIST ? [$db->retrieve_query($query)]
: $db->retrieve_query($query);
$db->commit();
LIST ? @{$result} : $result;
}
To avoid these infelicities, Contextual::Return provides a second way of
setting the result of a context block; a way that doesn't require that the
result be the last statement in the block:
return
LIST {
$db->start_work();
RESULT { $db->retrieve_query($query) };
$db->commit();
}
SCALAR {
$db->start_work();
RESULT { $db->retrieve_query($query) };
$db->commit();
}
The presence of a C<RESULT> block inside a contextual return block causes
that block to return the value of the final statement of the C<RESULT>
block as the handler's return value, rather than returning the value of
the handler's own final statement. In other words, the presence of a C<RESULT>
block overrides the normal return value of a context handler.
Better still, the C<RESULT> block always evaluates its final statement
in the same context as the surrounding C<return>, so you can just write:
return
VALUE {
$db->start_work();
RESULT { $db->retrieve_query($query) };
$db->commit();
}
and the C<retrieve_query()> method will be called in the appropriate context
in all cases.
A C<RESULT> block can appear anywhere inside any contextual return
block, but may not be used outside a context block. That is, this
is an error:
if ($db->closed) {
RESULT { undef }; # Error: not in a context block
}
return
VALUE {
$db->start_work();
RESULT { $db->retrieve_query($query) };
$db->commit();
}
=head2 Post-handler clean-up
If a subroutine uses an external resource, it's often necessary to close
or clean-up that resource after the subroutine ends...regardless of
whether the subroutine exits normally or via an exception.
Typically, this is done by encapsulating the resource in a lexically
scoped object whose destructor does the clean-up. However, if the clean-up
doesn't involve deallocation of an object (as in the C<< $db->commit() >>
example in the previous section), it can be annoying to have to create a
class and allocate a container object, merely to mediate the clean-up.
To make it easier to manage such resources, Contextual::Return supplies
a special labelled block: the C<RECOVER> block. If a C<RECOVER> block is
specified as part of a contextual return sequence, that block is
executed after any context handler, even if the context handler exits
via an exception.
So, for example, you could implement a simple commit-or-revert
policy like so:
return
LIST { $db->retrieve_all($query) }
SCALAR { $db->retrieve_next($query) }
RECOVER {
if ($@) {
$db->revert();
}
else {
$db->commit();
}
}
The presence of a C<RECOVER> block also intercepts all exceptions thrown
in any other context block in the same contextual return sequence. Any
such exception is passed into the C<RECOVER> block in the usual manner:
via the C<$@> variable. The exception may be rethrown out of the
C<RECOVER> block by calling C<die>:
return
LIST { $db->retrieve_all($query) }
DEFAULT { croak "Invalid call (not in list context)" }
RECOVER {
die $@ if $@; # Propagate any exception
$db->commit(); # Otherwise commit the changes
}
A C<RECOVER> block can also access or replace the returned value, by
invoking a C<RESULT> block. For example:
return
LIST { attempt_to_generate_list_for(@_) }
SCALAR { attempt_to_generate_count_for(@_) }
RECOVER {
if ($@) { # On any exception...
warn "Replacing return value. Previously: ", RESULT;
RESULT { undef } # ...return undef
}
}
=head2 Post-return clean-up
Occasionally it's necessary to defer the clean-up of resources until
after the return value has been used. Once again, this is usually
done by returning an object with a suitable destructor.
Using Contextual::Return you can get the same effect, by providing a
C<CLEANUP> block in the contextual return sequence:
return
LIST { $db->retrieve_all($query) }
SCALAR { $db->retrieve_next($query) }
CLEANUP { $db->commit() }
In this example, the C<commit> method call is only performed after the
return value has been used by the caller. Note that this is quite
different from using a C<RECOVER> block, which is called as the
subroutine returns its value; a C<CLEANUP> is called when the returned
value is garbage collected.
A C<CLEANUP> block is useful for controlling resources allocated to support an
C<ACTIVE> return value. For example:
my %file;
# Return an active value that is always the next line from a file...
sub readline_from {
my ($file_name) = @_;
# Open the file, if not already open...
if (!$file{$file_name}) {
open $file{$file_name}{handle}, '<', $file_name;
}
# Track how many active return values are using this file...
$file{$file_name}{count}++;
return ACTIVE
# Evaluating the return value returns the next line...
VALUE { readline $file{$file_name}{handle} }
# Once the active value is finished with, clean up the filehandle...
CLEANUP {
delete $file{$file_name}
if --$file{$file_name}{count} == 0;
}
}
=head2 Debugging contextual return values
Contextual return values are implemented as opaque objects (using the
"inside-out" technique). This means that passing such values to
Data::Dumper produces an uninformative output like:
$VAR1 = bless( do{\(my $o = undef)}, 'Contextual::Return::Value' );
So the module provides two methods that allow contextual return values
to be correctly reported: either directly, or when dumped by
Data::Dumper.
To dump a contextual return value directly, call the module's C<DUMP()>
method explicitly and print the result:
print $crv->Contextual::Return::DUMP();
This produces an output something like:
[
{ FROM => 'main::foo' },
{ NO_HANDLER => [ 'VOID', 'CODEREF', 'HASHREF', 'GLOBREF' ] },
{ FALLBACKS => [ 'VALUE' ] },
{ LIST => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] },
{ STR => '<<<Throws exception: Died at demo.pl line 7.>>>' },
{ NUM => 42 },
{ BOOL => -1 },
{ SCALARREF => '<<<self-reference>>>' },
{ ARRAYREF => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] },
];
The C<FROM> hash entry names the subroutine that produced the return
value. The C<NO_HANDLER> hash entry lists those contexts for which no
handler was defined (and which would therefore normally produce "can't
call" exceptions such as: C<"Can't call main::foo in VOID context">).
The C<FALLBACKS> hash entry lists any "generic" contexts such as
C<VALUE>, C<NONVOID>, C<REF>, C<DEFAULT>, etc. that the contextual
return value can also handle. After these, all the remaining hash
entries are actual contexts in which the return value could successfully
be evaluated, and the value it would produce in each of those contexts.
The Data::Dumper module also has a mechanism by which you can tell it
how to produce a similar listing automatically whenever a contextual
return value is passed to its C<Dumper> method. Data::Dumper allows you
to register a "freezer" method, that is called prior to dumping, and
which can be used to adapt an opaque object to make it dumpable.
Contextual::Return provides just such a method
(C<Contextual::Return::FREEZE()>) for you to register, like so:
use Data::Dumper 'Dumper';
local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
print Dumper $foo;
The output is then precisely the same as C<Contextual::Return::DUMP()>
would produce.
Note that, with both of the above dumping mechanisms, it is essential to use
the full name of the method. That is:
print $crv->Contextual::Return::DUMP();
rather than:
print $crv->DUMP();
This is because the shorter version is interpreted as calling the
C<DUMP()> method on the object returned by the return value's C<OBJREF>
context block (see L<"Scalar reference contexts">)
For the same reason, you must write:
local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE';
not:
local $Data::Dumper::Freezer = 'FREEZE';
=head2 Namespace controls
By default the module exports a large number of return context markers:
DEFAULT REF LAZY
VOID SCALARREF FIXED
NONVOID ARRAYREF ACTIVE
LIST CODEREF RESULT
SCALAR HASHREF RECOVER
VALUE GLOBREF CLEANUP
STR OBJREF RVALUE
NUM METHOD LVALUE
BOOL NVALUE
PUREBOOL
These are exported as subroutines, and so can conflict with existing
subroutines in your namespace, or with subroutines imported from other
modules.
Contextual::Return allows you to control which contextual return blocks are
exported into any namespace that uses the module. It also allows you to rename
blocks to avoid namespace conflicts with existing subroutines.
Both these features are controlled by passing arguments to the C<use>
statement that loads the module as follows:
=over
=item *
Any string passed as an argument to C<use Contextual::Return>,
exports only the block name it specifies;
=item *
Any regex passed as an argument to C<use Contextual::Return>
exports every block name it matches;
=item *
Any array ref (recursively) exports each of its elements
=item *
Any string that appears immediately after one of the above three specifiers,
and which is not itself a block name, renames the handlers exported by that
preceding specifier by filtering each handler name through C<sprintf()>
=back
That is, you can specify handlers to be exported by exact name (as a string),
by general pattern (as a regex), or collectively (in an array). And after any
of these export specifications, you can append a template in which any C<'%s'>
will be replaced by the original name of the handler. For example:
# Selectively export specific sets of handlers...
use Contextual::Return qr/[NLR]VALUE/;
use Contextual::Return qr/.*REF/;
# Selective export specific sets and add a suffix to each...
use Contextual::Return qr/[NLR]VALUE/ => '%s_CONTEXT';
# Selective export specific sets and add a prefix to each...
use Contextual::Return qr/.*REF/ => 'CR_%s';
# Export a list of handlers...
use Contextual::Return 'NUM', 'STR', 'BOOL' ;
use Contextual::Return qw< NUM STR BOOL >;
use Contextual::Return ['NUM', 'STR', 'BOOL'];
# Export a list of handlers, renaming them individually...
use Contextual::Return NUM => 'NUMERIC', STR => 'TEXT', BOOL => 'CR_%s';
# Export a list of handlers, renaming them collectively...
use Contextual::Return ['NUM', 'STR', 'BOOL'] => '%s_CONTEXT';
# Mixed exports and renames...
use Contextual::Return (
STR => 'TEXT',
['NUM', 'BOOL'] => 'CR_%s',
['LIST', 'SCALAR', 'VOID', qr/^[NLR]VALUE/] => '%s_CONTEXT',
);
=head1 INTERFACE
=head2 Context tests
=over
=item C<< LIST() >>
Returns true if the current subroutine was called in list context.
A cleaner way of writing: C<< wantarray() >>
=item C<< SCALAR() >>
Returns true if the current subroutine was called in scalar context.
A cleaner way of writing: C<< defined wantarray() && ! wantarray() >>
=item C<< VOID() >>
Returns true if the current subroutine was called in void context.
A cleaner way of writing: C<< !defined wantarray() >>
=item C<< NONVOID() >>
Returns true if the current subroutine was called in list or scalar context.
A cleaner way of writing: C<< defined wantarray() >>
=back
=head2 Standard contexts
=over
=item C<< LIST {...} >>
The block specifies what the context sequence should evaluate to when
called in list context.
=item C<< SCALAR {...} >>
The block specifies what the context sequence should evaluate to in
scalar contexts, unless some more-specific specifier scalar context specifier
(see below) also occurs in the same context sequence.
=item C<< VOID {...} >>
The block specifies what the context sequence should do when
called in void context.
=back
=head2 Scalar value contexts
=over
=item C<< BOOL {...} >>
The block specifies what the context sequence should evaluate to when
treated as a boolean value.
=item C<< NUM {...} >>
The block specifies what the context sequence should evaluate to when
treated as a numeric value.
=item C<< STR {...} >>
The block specifies what the context sequence should evaluate to when
treated as a string value.
=item C<< LAZY {...} >>
Another name for C<SCALAR {...}>. Usefully self-documenting when the primary
purpose of the contextual return is to defer evaluation of the return value
until it's actually required.
=back
=head2 Scalar reference contexts
=over
=item C<< SCALARREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to a scalar.
=item C<< ARRAYREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to an array.
=item C<< HASHREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to a hash.
Note that a common error here is to write:
HASHREF { a=>1, b=>2, c=>3 }
The curly braces there are a block, not a hash constructor, so the block
doesn't return a hash reference and the interpreter throws an exception.
What's needed is:
HASHREF { {a=>1, b=>2, c=>3} }
in which the inner braces I<are> a hash constructor.
=item C<< CODEREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to a subroutine.
=item C<< GLOBREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to a typeglob.
=item C<< OBJREF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference to an object.
=item C<< METHOD {...} >>
The block can be used to specify particular handlers for specific method calls
when the return value is treated as an object reference.
It should return a list of methodname/methodbody pairs. Each method name can
be specified as a string, a regex, or an array of strings or regexes. The
method bodies must be specified as subroutine references (usually anonymous
subs). The first method name that matches the actual method call selects the
corresponding handler, which is then called.
=back
=head2 Generic contexts
=over
=item C<< VALUE {...} >>
The block specifies what the context sequence should evaluate to when
treated as a non-referential value (as a boolean, numeric, string,
scalar, or list). Only used if there is no more-specific value context
specifier in the context sequence.
=item C<< REF {...} >>
The block specifies what the context sequence should evaluate to when
treated as a reference of any kind. Only used if there is no
more-specific referential context specifier in the context sequence.
=item C<< NONVOID {...} >>
The block specifies what the context sequence should evaluate to when
used in a non-void context of any kind. Only used if there is no
more-specific context specifier in the context sequence.
=item C<< DEFAULT {...} >>
The block specifies what the context sequence should evaluate to when
used in a void or non-void context of any kind. Only used if there is no
more-specific context specifier in the context sequence.
=back
=head2 Failure context
=over
=item C<< FAIL >>
This block is executed unconditionally and is used to indicate failure. In a
Boolean context it return false. In all other contexts it throws an exception
consisting of the final evaluated value of the block.
That is, using C<FAIL>:
return
FAIL { "Could not defenestrate the widget" }
is exactly equivalent to writing:
return
BOOL { 0 }
DEFAULT { croak "Could not defenestrate the widget" }
except that the reporting of errors is a little smarter under C<FAIL>.
If C<FAIL> is called without specifying a block:
return FAIL;
it is equivalent to:
return FAIL { croak "Call to <subname> failed" }
(where C<< <subname> >> is replaced with the name of the surrounding
subroutine).
Note that, because C<FAIL> implicitly covers every possible return
context, it cannot be chained with other context specifiers.
=item C<< Contextual::Return::FAIL_WITH >>
This subroutine is not exported, but may be called directly to reconfigure
C<FAIL> behaviour in the caller's namespace.
The subroutine is called with an optional string (the I<flag>), followed
by a mandatory hash reference (the I<configurations hash>), followed by a
list of zero-or-more strings (the I<selector list>). The values of the
configurations hash must all be subroutine references.
If the optional flag is specified, C<FAIL_WITH> searches the selector
list looking for that string, then uses the I<following> item in the
selector list as its I<selector value>. If that selector value is a
string, C<FAIL_WITH> looks up that key in the hash, and installs the
corresponding subroutine as the namespace's C<FAIL> handler (an
exception is thrown if the selector string is not a valid key of the
configurations hash). If the selector value is a subroutine reference,
C<FAIL_WITH> installs that subroutine as the C<FAIL> handler.
If the optional flag is I<not> specified, C<FAIL_WITH> searches the
entire selector list looking for the last element that matches any
key in the configurations hash. It then looks up that key in the
hash, and installs the corresponding subroutine as the namespace's
C<FAIL> handler.
See L<Configurable failure contexts> for examples of using this feature.
=back
=head2 Lvalue contexts
=over
=item C<< LVALUE >>
This block is executed when the result of an C<:lvalue> subroutine is assigned
to. The assigned value is passed to the block as C<$_>. To access the caller's
C<$_> value, use C<$CALLER::_>.
=item C<< RVALUE >>
This block is executed when the result of an C<:lvalue> subroutine is used
as an rvalue. The final value that is evaluated in the block becomes the
rvalue.
=item C<< NVALUE >>
This block is executed when an C<:lvalue> subroutine is evaluated in void
context.
=back
=head2 Explicit result blocks
=over
=item C<< RESULT >>
This block may only appear inside a context handler block. It causes the
surrounding handler to return the final value of the C<RESULT>'s block,
rather than the final value of the handler's own block. This override occurs
regardless of the location to the C<RESULT> block within the handler.
If called without a trailing C<{...}>, it simply returns the current result
value in scalar contexts, or the list of result values in list context.
=back
=head2 Recovery blocks
=over
=item C<< RECOVER >>
If present in a context return sequence, this block grabs control after
any context handler returns or exits via an exception. If an exception
was thrown it is passed to the C<RECOVER> block via the C<$@> variable.
=back
=head2 Clean-up blocks
=over
=item C<< CLEANUP >>
If present in a context return sequence, this block grabs control when
a return value is garbage collected.
=back
=head2 Modifiers
=over
=item C<< FIXED >>
This specifies that the scalar value will only be evaluated once, the
first time it is used, and that the value will then morph into that
evaluated value.
=item C<< ACTIVE >>
This specifies that the scalar value's originating block will be re-
evaluated every time the return value is used.
=back
=head2 Debugging support
=over
=item C<< $crv->Contextual::Return::DUMP() >>
Dump a representation of the return value in all viable contexts
=item C<< local $Data::Dumper::Freezer = 'Contextual::Return::FREEZE' >>
Configure Data::Dumper to correctly dump a representation of the
return value.
=back
=head1 DIAGNOSTICS
=over
=item C<Can't use %s as export specifier>
In your C<use Contextual::Return> statement you specified something (such as a
hash or coderef) that can't be used to select what the module exports. Make
sure the list of selectors includes only strings, regexes, or references to
arrays of strings or regexes.
=item C<use Contextual::Return qr{%s} didn't export anything>
In your C<use Contextual::Return> statement you specified a regex to select
which handlers to support, but the regex didn't select any handlers. Check
that the regex you're using actually does match at least one of the names of
the modules many handlers.
=item C<Can't export %s: no such handler>
In your C<use Contextual::Return> statement you specified a string as the
name of a context handler to be exported, but the module doesn't export a
handler of that name. Check the spelling for the requested export.
=item C<Can't call %s in %s context>
The subroutine you called uses a contextual return, but doesn't specify what
to return in the particular context in which you called it. You either need to
change the context in which you're calling the subroutine, or else add a
context block corresponding to the offending context (or perhaps a
C<DEFAULT {...}> block).
=item C<%s can't return a %s reference">
You called the subroutine in a context that expected to get back a
reference of some kind but the subroutine didn't specify the
corresponding C<SCALARREF>, C<ARRAYREF>, C<HASHREF>, C<CODEREF>,
C<GLOBREF>, or generic C<REF>, C<NONVOID>, or C<DEFAULT> handlers.
You need to specify the appropriate one of these handlers in the subroutine.
=item C<Can't call method '%s' on %s value returned by %s">
You called the subroutine and then tried to call a method on the return
value, but the subroutine returned a classname or object that doesn't
have that method. This probably means that the subroutine didn't return
the classname or object you expected. Or perhaps you need to specify
an C<OBJREF {...}> context block.
=item C<Can't install two %s handlers>
You attempted to specify two context blocks of the same name in the same
return context, which is ambiguous. For example:
sub foo: lvalue {
LVALUE { $foo = $_ }
RVALUE { $foo }
LVALUE { $foo = substr($_,1,10) }
}
or:
sub bar {
return
BOOL { 0 }
NUM { 1 }
STR { "two" }
BOOL { 1 };
}
Did you cut-and-paste wrongly, or mislabel one of the blocks?
=item C<Expected a %s block after the %s block but found instead: %s>
If you specify any of C<LVALUE>, C<RVALUE>, or C<NVALUE>, then you can only
specify C<LVALUE>, C<RVALUE>, or C<NVALUE> blocks in the same return context.
If you need to specify other contexts (like C<BOOL>, or C<STR>, or C<REF>,
etc.), put them inside an C<RVALUE> block. See L<Lvalue contexts> for an
example.
=item C<Call to %s failed at %s>
This is the default exception that a C<FAIL> throws in a non-scalar
context. Which means that the subroutine you called has signalled
failure by throwing an exception, and you didn't catch that exception.
You should either put the call in an C<eval {...}> block or else call the
subroutine in boolean context instead.
=item C<Call to %s failed at %s. Attempted to use failure value at %s>
This is the default exception that a C<FAIL> throws when a failure value
is captured in a scalar variable and later used in a non-boolean
context. That means that the subroutine you called must have failed, and
you didn't check the return value for that failure, so when you tried to
use that invalid value it killed your program. You should either put the
original call in an C<eval {...}> or else test the return value in a
boolean context and avoid using it if it's false.
=item C<Usage: FAIL_WITH $flag_opt, \%selector, @args>
The C<FAIL_WITH> subroutine expects an optional flag, followed by a reference
to a configuration hash, followed by a list or selector arguments. You gave it
something else. See L<Configurable Failure Contexts>.
=item C<Selector values must be sub refs>
You passed a configuration hash to C<FAIL_WITH> that specified non-
subroutines as possible C<FAIL> handlers. Since non-subroutines can't
possibly be handlers, maybe you forgot the C<sub> keyword somewhere?
=item C<Invalid option: %s => %s>
The C<FAIL_WITH> subroutine was passed a flag/selector pair, but the selector
was not one of those allowed by the configuration hash.
=item C<FAIL handler for package %s redefined>
A warning that the C<FAIL> handler for a particular package was
reconfigured more than once. Typically that's because the module was
loaded in two places with difference configurations specified. You can't
reasonably expect two different sets of behaviours from the one module within
the one namespace.
=back
=head1 CONFIGURATION AND ENVIRONMENT
Contextual::Return requires no configuration files or environment variables.
=head1 DEPENDENCIES
Requires version.pm and Want.pm.
=head1 INCOMPATIBILITIES
C<LVALUE>, C<RVALUE>, and C<NVALUE> do not work correctly under the Perl
debugger. This seems to be because the debugger injects code to capture
the return values from subroutines, which interferes destructively with
the optional final arguments that allow C<LVALUE>, C<RVALUE>, and C<NVALUE>
to cascade within a single return.
=head1 BUGS AND LIMITATIONS
No bugs have been reported.
=head1 AUTHOR
Damian Conway C<< <DCONWAY@cpan.org> >>
=head1 LICENCE AND COPYRIGHT
Copyright (c) 2005-2006, Damian Conway C<< <DCONWAY@cpan.org> >>. All rights reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
|