File: Devel.html

package info (click to toggle)
libhtml-mason-perl 1%3A1.39-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 2,072 kB
  • ctags: 1,535
  • sloc: perl: 17,624; sh: 187; makefile: 12
file content (2162 lines) | stat: -rw-r--r-- 97,837 bytes parent folder | download
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
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML::Mason::Devel - Mason Developer's Manual</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:root@localhost" />
</head>

<body style="background-color: white">

<p><A NAME="__index__"></a></p>
<!-- INDEX BEGIN -->

<ul>

	<li><A HREF="#name">NAME</a></li>
	<li><A HREF="#description">DESCRIPTION</a></li>
	<li><A HREF="#how_to_use_this_manual">HOW TO USE THIS MANUAL</a></li>
	<li><A HREF="#what_are_components">WHAT ARE COMPONENTS?</a></li>
	<li><A HREF="#inline_perl_sections">IN-LINE PERL SECTIONS</a></li>
	<ul>

		<li><A HREF="#examples_and_recommended_usage">Examples and Recommended Usage</a></li>
	</ul>

	<li><A HREF="#mason_objects">MASON OBJECTS</a></li>
	<ul>

		<li><A HREF="#request_objects">Request Objects</a></li>
		<li><A HREF="#component_objects">Component Objects</a></li>
		<li><A HREF="#system_objects">System Objects</a></li>
	</ul>

	<li><A HREF="#calling_components">CALLING COMPONENTS</a></li>
	<ul>

		<li><A HREF="#components_that_output_html">Components that output HTML</a></li>
		<li><A HREF="#component_calls_with_content">Component Calls with Content</a></li>
		<li><A HREF="#advanced_components_calls_with_c">Advanced Components Calls with Content</a></li>
		<li><A HREF="#components_that_return_values">Components that Return Values</a></li>
		<li><A HREF="#subrequests">Subrequests</a></li>
	</ul>

	<li><A HREF="#toplevel_components">TOP-LEVEL COMPONENTS</a></li>
	<ul>

		<li><A HREF="#dhandlers">dhandlers</a></li>
		<li><A HREF="#autohandlers">autohandlers</a></li>
		<li><A HREF="#dhandlers_vs__autohandlers">dhandlers vs. autohandlers</a></li>
	</ul>

	<li><A HREF="#passing_parameters">PASSING PARAMETERS</a></li>
	<ul>

		<li><A HREF="#in_component_calls">In Component Calls</a></li>
		<li><A HREF="#in_http_requests">In HTTP requests</a></li>
		<li><A HREF="#accessing_parameters">Accessing Parameters</a></li>
		<li><A HREF="#parameter_passing_examples">Parameter Passing Examples</a></li>
		<li><A HREF="#using____instead">Using @_ instead</a></li>
	</ul>

	<li><A HREF="#initialization_and_cleanup">INITIALIZATION AND CLEANUP</a></li>
	<ul>

		<li><A HREF="#__init_">&lt;%init&gt;</a></li>
		<li><A HREF="#__cleanup_">&lt;%cleanup&gt;</a></li>
		<li><A HREF="#__once_">&lt;%once&gt;</a></li>
		<li><A HREF="#__shared_">&lt;%shared&gt;</a></li>
	</ul>

	<li><A HREF="#embedded_components">EMBEDDED COMPONENTS</a></li>
	<ul>

		<li><A HREF="#__def_name_">&lt;%def <em>name</em>&gt;</a></li>
		<li><A HREF="#__method_name_">&lt;%method <em>name</em>&gt;</a></li>
	</ul>

	<li><A HREF="#flags_and_attributes">FLAGS AND ATTRIBUTES</a></li>
	<ul>

		<li><A HREF="#__flags_">&lt;%flags&gt;</a></li>
		<li><A HREF="#__attr_">&lt;%attr&gt;</a></li>
	</ul>

	<li><A HREF="#filtering">FILTERING</a></li>
	<ul>

		<li><A HREF="#__filter__section">&lt;%filter&gt; section</a></li>
	</ul>

	<li><A HREF="#comment_markers">COMMENT MARKERS</a></li>
	<ul>

		<li><A HREF="#__doc_">&lt;%doc&gt;</a></li>
		<li><A HREF="#_____comment______">&lt;% # comment... %&gt;</a></li>
		<li><A HREF="#___comment">%# comment</a></li>
		<li><A HREF="#__if__0_____">% if (0) { }</a></li>
		<li><A HREF="#html_xml_____comments">HTML/XML/... comments</a></li>
	</ul>

	<li><A HREF="#other_syntax">OTHER SYNTAX</a></li>
	<ul>

		<li><A HREF="#__text_">&lt;%text&gt;</a></li>
		<li><A HREF="#escaping_expressions">Escaping expressions</a></li>
		<ul>

			<li><A HREF="#userdefined_escapes">User-defined Escapes</a></li>
			<li><A HREF="#manually_applying_escapes">Manually applying escapes</a></li>
		</ul>

		<li><A HREF="#backslash_at_end_of_line">Backslash at end of line</a></li>
	</ul>

	<li><A HREF="#data_caching">DATA CACHING</a></li>
	<ul>

		<li><A HREF="#basic_usage">Basic Usage</a></li>
		<li><A HREF="#multiple_keys_values">Multiple Keys/Values</a></li>
		<li><A HREF="#expiration">Expiration</a></li>
		<li><A HREF="#avoiding_concurrent_recomputatio">Avoiding Concurrent Recomputation</a></li>
		<li><A HREF="#caching_all_output">Caching All Output</a></li>
		<li><A HREF="#cache_object">Cache Object</a></li>
		<li><A HREF="#choosing_a_cache_subclass__with_">Choosing a Cache Subclass - with Cache::Cache</a></li>
		<li><A HREF="#choosing_a_cache_subclass__with_">Choosing a Cache Subclass - with CHI</a></li>
		<li><A HREF="#accessing_a_cache_externally">Accessing a Cache Externally</a></li>
		<li><A HREF="#mason_1_0x_cache_api">Mason 1.0x Cache API</a></li>
	</ul>

	<li><A HREF="#webspecific_features">WEB-SPECIFIC FEATURES</a></li>
	<ul>

		<li><A HREF="#sending_http_headers">Sending HTTP Headers</a></li>
		<li><A HREF="#returning_http_status">Returning HTTP Status</a></li>
		<ul>

			<li><A HREF="#filters_and__m_abort">Filters and $m-&gt;abort</a></li>
		</ul>

		<li><A HREF="#external_redirects">External Redirects</a></li>
		<li><A HREF="#internal_redirects">Internal Redirects</a></li>
	</ul>

	<li><A HREF="#using_the_perl_debugger">USING THE PERL DEBUGGER</a></li>
	<li><A HREF="#objectoriented_techniques">OBJECT-ORIENTED TECHNIQUES</a></li>
	<ul>

		<li><A HREF="#determining_inheritance">Determining inheritance</a></li>
		<li><A HREF="#content_wrapping">Content wrapping</a></li>
		<li><A HREF="#accessing_methods_and_attributes">Accessing methods and attributes</a></li>
		<li><A HREF="#sharing_data">Sharing data</a></li>
		<li><A HREF="#example">Example</a></li>
	</ul>

	<li><A HREF="#common_traps">COMMON TRAPS</a></li>
	<li><A HREF="#mason_and_source_filters">MASON AND SOURCE FILTERS</a></li>
	<li><A HREF="#authors">AUTHORS</a></li>
	<li><A HREF="#see_also">SEE ALSO</a></li>
</ul>
<!-- INDEX END -->

<hr />
<p>
</p>
<h1><A NAME="name">NAME</a></h1>
<p>HTML::Mason::Devel - Mason Developer's Manual</p>
<p>
</p>
<hr />
<h1><A NAME="description">DESCRIPTION</a></h1>
<p>This manual is written for content developers who know HTML and at
least a little Perl. The goal is to write, run, and debug Mason
components.</p>
<p>If you are the webmaster (or otherwise responsible for the Mason
installation), you should also read <a HREF="Admin.html">the administrator's manual</a>. There you will find information about site
configuration, performance tuning, component caching, and so on.</p>
<p>If you are a developer just interested in knowing more about Mason's
capabilities and implementation, then <a HREF="Admin.html">the administrator's manual</a> is for you too.</p>
<p>We strongly suggest that you have a working Mason to play with as you
work through these examples. Other component examples can be found in
the <code>samples/</code> directory.</p>
<p>While Mason can be used for tasks besides implementing a dynamic web
site, that is what <em>most</em> people want to do with Mason, and is thus
the focus of this manual.</p>
<p>If you are planning to use Mason outside of the web, this manual will
still be useful, of course.  Also make sure to read the <A HREF="Admin.html#running_outside_of_mod_perl">running outside of mod_perl</a> section of the administrator's manual.</p>
<p>
</p>
<hr />
<h1><A NAME="how_to_use_this_manual">HOW TO USE THIS MANUAL</a></h1>
<p>If you are just learning Mason and want to get started quickly, we
recommend the following sections:</p>
<p>o <A HREF="#what_are_components">What Are Components?</a></p>
<p>o <A HREF="#inline_perl_sections">In-Line Perl Sections</a></p>
<p>o <A HREF="#calling_components">Calling Components</a></p>
<p>o <A HREF="#toplevel_components">Top-Level Components</a></p>
<p>o <A HREF="#passing_parameters">Passing Parameters</a></p>
<p>o <A HREF="#initialization_and_cleanup">Initialization and Cleanup</a> (mainly <code>&lt;%init&gt;</code>)</p>
<p>o <A HREF="#webspecific_features">Web-Specific Features</a></p>
<p>o <A HREF="#common_traps">Common Traps</a></p>
<p>
</p>
<hr />
<h1><A NAME="what_are_components">WHAT ARE COMPONENTS?</a></h1>
<p>The component - a mix of Perl and HTML - is Mason's basic building
block and computational unit. Under Mason, web pages are formed by
combining the output from multiple components.  An article page for a
news publication, for example, might call separate components for the
company masthead, ad banner, left table of contents, and article
body. Consider this layout sketch:</p>
<pre>
    +---------+------------------+
    |Masthead | Banner Ad        |
    +---------+------------------+
    |         |                  |
    |+-------+|Text of Article ..|
    ||       ||                  |
    ||Related||Text of Article ..|
    ||Stories||                  |
    ||       ||Text of Article ..|
    |+-------+|                  |
    |         +------------------+
    |         | Footer           |
    +---------+------------------+</pre>
<p>The top level component decides the overall page layout, perhaps with
HTML tables. Individual cells are then filled by the output of
subordinate components, one for the Masthead, one for the Footer,
etc. In practice pages are built up from as few as one, to as many as
twenty or more components.</p>
<p>This component approach reaps many benefits in a web environment. The
first benefit is <em>consistency</em>: by embedding standard design
elements in components, you ensure a consistent look and make it
possible to update the entire site with just a few edits. The second
benefit is <em>concurrency</em>: in a multi-person environment, one person
can edit the masthead while another edits the table of contents.  A
last benefit is <em>reuseability</em>: a component produced for one site
might be useful on another. You can develop a library of generally
useful components to employ on your sites and to share with others.</p>
<p>Most components emit chunks of HTML. ``Top level'' components, invoked
from a URL, represent an entire web page. Other, subordinate
components emit smaller bits of HTML destined for inclusion in top
level components.</p>
<p>Components receive form and query data from HTTP requests. When called
from another component, they can accept arbitrary parameter lists just
like a subroutine, and optionally return values.  This enables a type
of component that does not print any HTML, but simply serves as a
function, computing and returning a result.</p>
<p>Mason actually compiles components down to Perl subroutines, so you
can debug and profile component-based web pages with standard Perl
tools that understand the subroutine concept, e.g. you can use the
Perl debugger to step through components, and <strong>Devel::DProf</strong> to
profile their performance.</p>
<p>
</p>
<hr />
<h1><A NAME="inline_perl_sections">IN-LINE PERL SECTIONS</a></h1>
<p>Here is a simple component example:</p>
<pre>
    &lt;%perl&gt;
    my $noun = 'World';
    my @time = localtime;
    &lt;/%perl&gt;
    Hello &lt;% $noun %&gt;,
    % if ( $time[2] &lt; 12 ) {
    good morning.
    % } else {
    good afternoon.
    % }</pre>
<p>After 12 pm, the output of this component is:</p>
<pre>
    Hello World, good afternoon.</pre>
<p>This short example demonstrates the three primary ``in-line'' Perl
sections. In-line sections are generally embedded within HTML and
execute in the order they appear. Other sections (<code>&lt;%init&gt;</code>,
<code>&lt;%args&gt;</code>, etc.) are tied to component events like initialization,
cleanup, and argument definition.</p>
<p>The parsing rules for these Perl sections are as follows:</p>
<ol>
<li>
<p>Blocks of the form &lt;% xxx %&gt; are replaced with the result of
evaluating xxx as a single Perl expression.  These are often used for
variable replacement. such as 'Hello, &lt;% $name %&gt;!'.</p>
</li>
<li>
<p>Lines beginning with a '%' character are treated as Perl.</p>
</li>
<li>
<p>Multiline blocks of Perl code can be inserted with the <code>&lt;%perl&gt;</code>
.. <code>&lt;/%perl&gt;</code> tag. The enclosed text is executed as Perl and the return
value, if any, is discarded.</p>
<p>The <code>&lt;%perl&gt;</code> tag, like all block tags in Mason, is
case-insensitive. It may appear anywhere in the text, and may span any
number of lines.</p>
</li>
</ol>
<p>
</p>
<h2><A NAME="examples_and_recommended_usage">Examples and Recommended Usage</a></h2>
<p><strong>% lines</strong></p>
<p>Most useful for conditional and loop structures - if, while, foreach,
, etc. - as well as side-effect commands like assignments. To improve
readability, always put a space after the '%'. Examples:</p>
<p>o Conditional code</p>
<pre>
    % my $ua = $r-&gt;header_in('User-Agent');
    % if ($ua =~ /msie/i) {
    Welcome, Internet Explorer users
    ...
    % } elsif ($ua =~ /mozilla/i) {
    Welcome, Netscape users
    ...
    % }</pre>
<p>o HTML list formed from array</p>
<pre>
    &lt;ul&gt;
    % foreach $item (@list) {
    &lt;li&gt;&lt;% $item %&gt;&lt;/li&gt;
    % }
    &lt;/ul&gt;</pre>
<p>o HTML list formed from hash</p>
<pre>
    &lt;ul&gt;
    % while (my ($key,$value) = each(%ENV)) {
    &lt;li&gt;
    &lt;b&gt;&lt;% $key %&gt;&lt;/b&gt;: &lt;% $value %&gt;
    &lt;/li&gt;
    % }
    &lt;/ul&gt;</pre>
<p>o HTML table formed from list of hashes</p>
<pre>
    &lt;table&gt;
    % foreach my $h (@loh) {
    &lt;tr&gt;
    &lt;td&gt;&lt;% $h-&gt;{foo} %&gt;&lt;/td&gt;
    &lt;td bgcolor=#ee0000&gt;&lt;% $h-&gt;{bar} %&gt;&lt;/td&gt;
    &lt;td&gt;&lt;% $h-&gt;{baz} %&gt;&lt;/td&gt;
    &lt;/tr&gt;
    % }
    &lt;/table&gt;</pre>
<p><strong>&lt;% xxx %</strong> &gt;&gt;</p>
<p>Most useful for printing out variables, as well as more complex
expressions. To improve readability, always separate the tag
and expression with spaces. Examples:</p>
<pre>
  Dear &lt;% $name %&gt;: We will come to your house at &lt;% $address %&gt; in the
  fair city of &lt;% $city %&gt; to deliver your $&lt;% $amount %&gt; dollar prize!</pre>
<pre>
  The answer is &lt;% ($y+8) % 2 %&gt;.</pre>
<pre>
  You are &lt;% $age &lt; 18 ? 'not' : '' %&gt; permitted to enter this site.</pre>
<p><strong>&lt;%perl</strong> xxx &lt;/%perl&gt; &gt;&gt;</p>
<p>Useful for Perl blocks of more than a few lines.</p>
<p>
</p>
<hr />
<h1><A NAME="mason_objects">MASON OBJECTS</a></h1>
<p>This section describes the various objects in the Mason universe.
If you're just starting out, all you need to worry about initially
are the request objects.</p>
<p>
</p>
<h2><A NAME="request_objects">Request Objects</a></h2>
<p>Two global per-request objects are available to all components: $r and
$m.</p>
<p>$r, the mod_perl request object, provides a Perl API to the current
Apache request.  It is fully described in Apache.pod. Here is a
sampling of methods useful to component developers:</p>
<pre>
    $r-&gt;uri             # the HTTP request URI
    $r-&gt;header_in(..)   # get the named HTTP header line
    $r-&gt;content_type    # set or retrieve content-type
    $r-&gt;header_out(..)  # set or retrieve an outgoing header</pre>
<pre>
    $r-&gt;content         # don't use this one! (see Tips and Traps)</pre>
<p>$m, the Mason request object, provides an analogous API for
Mason. Almost all Mason features not activated by syntactic tags are
accessed via $m methods.  You'll be introduced to these methods
throughout this document as they are needed.  For a description of all
methods see <strong><a HREF="Request.html">HTML::Mason::Request</a></strong>.</p>
<p>Because these are always set inside components, you should not ever
define other variables with the same name, or else your code may fail
in strange and mysterious ways.</p>
<p>
</p>
<h2><A NAME="component_objects">Component Objects</a></h2>
<p>Mason provides an object API for components, allowing you to query a
component's various asociated files, arguments, etc. For a description
of all methods see
<strong><a HREF="Component.html">HTML::Mason::Component</a></strong>.  Typically you
get a handle on a component object from request methods like <code>&lt;
$m-</code>current_comp &gt;&gt; and <code>$m-&gt;fetch_comp</code>.</p>
<p>Note that for many basic applications all you'll want to do with
components is call them, for which no object method is needed. See
next section.</p>
<p>
</p>
<h2><A NAME="system_objects">System Objects</a></h2>
<p>Many system objects share the work of serving requests in Mason:
<a HREF="Lexer.html">HTML::Mason::Lexer</a>,
<a HREF="Compiler.html">HTML::Mason::Compiler</a>,
<a HREF="Interp.html">HTML::Mason::Interp</a>,
<a HREF="Resolver.html">HTML::Mason::Resolver</a>,
and <a HREF="ApacheHandler.html">HTML::Mason::ApacheHandler</a> are examples. The
administrator creates these objects and provides parameters that shape
Mason's behavior. As a pure component developer you shouldn't need to
worry about or access these objects, but occasionally we'll mention a
relevant parameter.</p>
<p>
</p>
<hr />
<h1><A NAME="calling_components">CALLING COMPONENTS</a></h1>
<p>Mason pages often are built not from a single component, but from
multiple components that call each other in a hierarchical fashion.</p>
<p>
</p>
<h2><A NAME="components_that_output_html">Components that output HTML</a></h2>
<p>To call one component from another, use the &lt;&amp; &amp;&gt; tag:</p>
<pre>
    &lt;&amp; comp_path, [name=&gt;value, ...] &amp;&gt;</pre>
<dl>
<dt><strong><A NAME="item_comp_path_3a">comp_path:</a></strong>

<dd>
<p>The component path. With a leading '/', the path is relative to the
component root (<A HREF="Params.html#comp_root">comp_root</a>). Otherwise, it is relative to the
location of the calling component.</p>
</dd>
</li>
<dt><strong><A NAME="item_name__3d_3e_value_pairs_3a">name =&gt; value pairs:</a></strong>

<dd>
<p>Parameters are passed as one or more <code>name =&gt; value</code> pairs,
e.g. <code>player&nbsp;=&gt;&nbsp;'M.&nbsp;Jordan'</code>.</p>
</dd>
</li>
</dl>
<p>comp_path may be a literal string (quotes optional) or a Perl expression
that evaluates to a string. To eliminate the need for quotes in most
cases, Mason employs some magic parsing: If the first character is
one of <code>[\w/_.]</code>, comp_path is assumed to be a literal
string running up to the first comma or &amp;&gt;. Otherwise, comp_path
is evaluated as an expression.</p>
<p>Here are some examples:</p>
<pre>
    # relative component paths
    &lt;&amp; topimage &amp;&gt;
    &lt;&amp; tools/searchbox &amp;&gt;</pre>
<pre>
    # absolute component path
    &lt;&amp; /shared/masthead, color=&gt;'salmon' &amp;&gt;</pre>
<pre>
    # this component path MUST have quotes because it contains a comma
    &lt;&amp; &quot;sugar,eggs&quot;, mix=&gt;1 &amp;&gt;</pre>
<pre>
    # variable component path
    &lt;&amp; $comp &amp;&gt;</pre>
<pre>
    # variable component and arguments
    &lt;&amp; $comp, %args &amp;&gt;</pre>
<pre>
    # you can use arbitrary expression for component path, but it cannot
    # begin with a letter or number; delimit with () to remedy this
    &lt;&amp; (int(rand(2)) ? 'thiscomp' : 'thatcomp'), id=&gt;123 &amp;&gt;</pre>
<p>Several request methods also exist for calling components.  <code>$m-&gt;comp</code>
performs the equivalent action to &lt;&amp; &amp;&gt;:</p>
<pre>
    $m-&gt;comp('/shared/masthead', color=&gt;'salmon');</pre>
<p><code>$m-&gt;scomp</code> is like the sprintf version of <code>$m-&gt;comp</code>: it returns
the component output, allowing the caller to examine and modify it
before printing:</p>
<pre>
    my $masthead = $m-&gt;scomp('/shared/masthead', color=&gt;'salmon');
    $masthead =~ ...;
    $m-&gt;print($masthead);</pre>
<p>
</p>
<h2><A NAME="component_calls_with_content">Component Calls with Content</a></h2>
<p>Components can be used to filter part of the page's content using an
extended component syntax.</p>
<pre>
    &lt;&amp;| /path/to/comp &amp;&gt; this is the content &lt;/&amp;&gt;
    &lt;&amp;| comp, arg1 =&gt; 'hi' &amp;&gt; filters can take arguments &lt;/&amp;&gt;
    &lt;&amp;| comp &amp;&gt; content can include &lt;% &quot;tags&quot; %&gt; of all kinds &lt;/&amp;&gt;
    &lt;&amp;| comp1 &amp;&gt; nesting is also &lt;&amp;| comp2 &amp;&gt; OK &lt;/&amp;&gt; &lt;/&amp;&gt;
    &lt;&amp;| SELF:method1 &amp;&gt; subcomponents can be filters &lt;/&amp;&gt;</pre>
<p>The filtering component can be called in all the same ways a normal
component is called, with arguments and so forth.  The only difference
between a filtering component and a normal component is that a
filtering component is expected to fetch the content by calling
$m-&gt;content and do something with it.</p>
<p>The ending tag may optionally contain the name of the component, and Mason
will verify that it matches the name in the starting tag.  This may
be helpful when the tags are far apart or nested.  To avoid 
ambiguous situations, this is only allowed when the component name
is an unquoted literal (starting with <code>[\w/_.]</code>).  For anything
more complicated, such as <code>&lt;|&amp; $var &amp;&gt;</code> or <code>&lt;&amp;| 'name' &amp;&gt;</code>,
the simple <code>&lt;/&amp;&gt;</code> form must be used.</p>
<pre>
   &lt;&amp;| &quot;outer&quot; &amp;&gt;
     &lt;&amp;| /inner/comp, arg=&gt;'this' &amp;&gt;
       &lt;&amp;| .mycomp &amp;&gt;
          Yada yada yada
       &lt;/&amp; .mycomp &gt;
     &lt;/&amp; /inner/comp &gt;
   &lt;/&amp;&gt;</pre>
<p>Here is an example of a component used for localization.  Its content
is a series of strings in different languages, and it selects the
correct one based on a global <code>$lang</code> variable, which could be setup
in a site-level autohandler.</p>
<pre>
   &lt;&amp;| /i18n/itext &amp;&gt;
      &lt;en&gt;Hello, &lt;% $name %&gt; This is a string in English&lt;/en&gt;
      &lt;de&gt;Schoene Gruesse, &lt;% $name %&gt;, diese Worte sind auf Deutsch&lt;/de&gt;
      &lt;pig&gt;ellohay &lt;% substr($name,2).substr($name,1,1).'ay' %&gt;,
      isthay isay igpay atinlay&lt;/pig&gt;
   &lt;/&amp;&gt;</pre>
<p>Here is the <em>/i18n/itext</em> component:</p>
<pre>
   &lt;% $text %&gt;</pre>
<pre>
   &lt;%init&gt;
   # this assumes $lang is a global variable which has been set up earlier.
   local $_ = $m-&gt;content;
   my ($text) = m{&lt;$lang&gt;(.*?)&lt;/$lang&gt;};
   &lt;/%init&gt;</pre>
<p>You can explicitly check whether a component has passed content by
checking the boolean <code>$m-&gt;has_content</code>.  This allows you to write
a component that will do different things depending on whether it was
passed content. However, before overloading a component in this way,
consider whether splitting the behavior into two distinct components
would work as well.</p>
<p>If a normal component which does not call <A HREF="#item_content"><code>$m-&gt;content</code></a> is called
with content, the content will not be output.</p>
<p>If you wrap a filtering component call around the entire component,
the result will be functionally similar to a <code>&lt;%filter&gt;</code> section.
See also <A HREF="#filtering">Filtering</a>.</p>
<p>
</p>
<h2><A NAME="advanced_components_calls_with_c">Advanced Components Calls with Content</a></h2>
<p>Internally <A HREF="#item_content"><code>$m-&gt;content</code></a> is implemented with a closure containing
the part of the component which is the content.  In English, that
means that any mason tags and perl code in the content are evaluated
when <A HREF="#item_content"><code>$m-&gt;content</code></a> is called, and <A HREF="#item_content"><code>$m-&gt;content</code></a> returns the
text which would have been output by mason.  Because the contents are
evaluated at the time that <A HREF="#item_content"><code>$m-&gt;content</code></a> is called, one can write
components which act as control structures or which output their
contents multiple times with different values for the variables (can
you say taglibs?).</p>
<p>The tricky part of using filter components as control structures is
setting up variables which can be accessed from both the filter
component and the content, which is in the component which calls the
filter component.  The content has access to all variables in the
surrounding component, but the filtering component does not.  There
are two ways to do this: use global variables, or pass a reference to
a lexical variable to the filter component.</p>
<p>Here is a simple example using the second method:</p>
<pre>
    % my $var;
    &lt;ol&gt;
    &lt;&amp;| list_items , list =&gt; \@items, var =&gt; \$var &amp;&gt;
    &lt;li&gt; &lt;% $var %&gt;&lt;/li&gt;
    &lt;/&amp;&gt;
    &lt;/ol&gt;</pre>
<p>list_items component:</p>
<pre>
    &lt;%args&gt;
    @list
    $var
    &lt;/%args&gt;
    % foreach (@list) {
    % $$var = $_;  # $var is a reference
    &lt;% $m-&gt;content %&gt;
    % }</pre>
<p>Using global variables can be somewhat simpler.  Below is the same
example, with <code>$var</code> defined as a global variable.  The site
administrator must make sure that <code>$var</code> is included in Mason's
allow_globals parameter.  Local-izing <code>$var</code> within the filter
component will allow the list_items component to be nested.</p>
<pre>
    &lt;ol&gt;
    &lt;&amp;| list_items, list =&gt; \@items &amp;&gt;
    &lt;li&gt; &lt;% $var %&gt;&lt;/li&gt;
    &lt;/&amp;&gt;
    &lt;/ol&gt;</pre>
<p>list_items component:</p>
<pre>
    &lt;%args&gt;
    @list
    &lt;/%args&gt;
    % foreach (@list) {
    % local $var = $_;
    &lt;% $m-&gt;content %&gt;
    % }</pre>
<p>Besides remembering to include <code>$var</code> in allow_globals, the
developers should take care not to use that variable is other places
where it might conflict with usage by the filter component.
Local-izing $var will also provide some protection against using it in
other places.</p>
<p>An even simpler method is to use the <code>$_</code> variable.  It is already
global, and is automatically local-ized by the foreach statement:</p>
<pre>
    &lt;ol&gt;
    &lt;&amp;| list_items, list =&gt; \@items &amp;&gt;
    &lt;li&gt; &lt;% $_ %&gt; &lt;/li&gt;
    &lt;/&amp;&gt;
    &lt;/ol&gt;</pre>
<p>list_items component:</p>
<pre>
    &lt;%args&gt;
    @list
    &lt;/%args&gt;
    % foreach (@list) {
    &lt;% $m-&gt;content %&gt;
    % }</pre>
<p>
</p>
<h2><A NAME="components_that_return_values">Components that Return Values</a></h2>
<p>So far you have seen components used solely to output HTML.  However,
components may also be used to return values.</p>
<p>While we will demonstrate how this is done, we strongly encourage you
to put code like this in modules instead.  There are several reasons
why this is a good idea:</p>
<ul>
<li>
<p>You can re-use this code outside of Mason.</p>
</li>
<li>
<p>It is easy to preload module code when running under mod_perl, which
can lower memory usage.</p>
</li>
<li>
<p>Using Mason components as subroutines is slower than just using
modules to do the same thing.</p>
</li>
<li>
<p>It's easier to regression test module code.</p>
</li>
</ul>
<p>With that being said, there are times when you may want to write a
component which returns a value.</p>
<p>As an example, you might have a component <code>is_netscape</code> that analyzes
the user agent to determine whether it is a Netscape browser:</p>
<pre>
    &lt;%init&gt;
    my $ua = $r-&gt;header_in('User-Agent');
    return ($ua =~ /Mozilla/i &amp;&amp; $ua !~ /MSIE/i) ? 1 : 0;
    &lt;/%init&gt;</pre>
<p>Because components are implemented underneath with Perl subroutines,
they can return values and even understand scalar/list
context. e.g. The result of <code>wantarray()</code> inside a component will reflect
whether the component was called in scalar or list context.</p>
<p>The &lt;&amp; &amp;&gt; notation only calls a component for its side-effect, and
discards its return value, if any.  To get at the return value of a
component, use the <code>$m-&gt;comp</code> command:</p>
<pre>
    % if ($m-&gt;comp('is_netscape')) {
    Welcome, Netscape user!
    % }</pre>
<p>Mason adds a <code>return undef</code> to the bottom of each component to
provide an empty default return value. To return your own value from a
component, you <em>must</em> use an explicit <code>return</code> statement. You cannot
rely on the usual Perl trick of letting return values ``fall through''.</p>
<p>While it is possible for a component to generate output <strong>and</strong> return
values, there is very little reason for a component to do both. For
example, it would not be very friendly for <code>is_netscape</code> to output
``hi Mom'' while it was computing its value, thereby surprising the
<code>if</code> statement! Conversely, any value returned by an output
generating component would typically be discarded by the &lt;&amp; &amp;&gt; tag
that invoked it.</p>
<p>
</p>
<h2><A NAME="subrequests">Subrequests</a></h2>
<p>You may sometimes want to have a component call go through all the
steps that the initial component call goes through, such as checking
for autohandlers and dhandlers.  To do this, you need to execute a
subrequest.</p>
<p>A subrequest is simply a Mason Request object and has all of the
methods normally associated with one.</p>
<p>To create a subrequest you simply use the <code>$m-&gt;make_subrequest</code>
method.  This method can take any parameters belonging to
<a HREF="Request.html">HTML::Mason::Request</a>, such as <A HREF="Params.html#autoflush">autoflush</a> or
<A HREF="Params.html#out_method">out_method</a>.  Once you have a new request object you simply call its
<code>exec</code> method to execute it, which takes exactly the same parameters
as the <code>comp</code> method.</p>
<p>Since subrequests inherit their parent request's parameters, output
from a component called via a subrequest goes to the same desintation
as output from components called during the parent request.  Of course,
you can change this.</p>
<p>Here are some examples:</p>
<pre>
  &lt;%perl&gt;
   my $req = $m-&gt;make_subrequest( comp =&gt; '/some/comp', args =&gt; [ id =&gt; 172 ] );
   $req-&gt;exec;
  &lt;/%perl&gt;</pre>
<p>If you want to capture the subrequest's output in a scalar, you can
simply pass an <A HREF="Params.html#out_method">out_method</a> parameter to <code>$m-&gt;make_subrequest</code>:</p>
<pre>
  &lt;%perl&gt;
   my $buffer;
   my $req =
       $m-&gt;make_subrequest
           ( comp =&gt; '/some/comp', args =&gt; [ id =&gt; 172 ], out_method =&gt; \$buffer );
   $req-&gt;exec;
  &lt;/%perl&gt;</pre>
<p>Now <code>$buffer</code> contains all the output from that call to <em>/some/comp</em>.</p>
<p>For convenience, Mason also provides an <code>$m-&gt;subexec</code> method.
This method takes the same arguments as <code>$m-&gt;comp</code> and internally
calls <code>$m-&gt;make_subrequest</code> and then <code>exec</code> on the created
request, all in one fell swoop.  This is useful in cases where you
have no need to override any of the parent request object's
attributes.</p>
<p>By default, output from a subrequest appears inline in the calling
component, at the point where it is executed.  If you wish to do
something else, you will need to explicitly override the subrequest's
<A HREF="Params.html#out_method">out_method</a> parameter.</p>
<p>Mason Request objects are only designed to handle a single call to
<code>exec</code>.  If you wish to make multiple subrequests, you must create
a new subrequest object for each one.</p>
<p>
</p>
<hr />
<h1><A NAME="toplevel_components">TOP-LEVEL COMPONENTS</a></h1>
<p>The first component invoked for a page (the ``top-level component'')
resides within the DocumentRoot and is chosen based on the URL. For
example:</p>
<pre>
    <a href="http://www.foo.com/mktg/prods.html?id=372">http://www.foo.com/mktg/prods.html?id=372</a></pre>
<p>Mason converts this URL to a filename,
e.g. <em>/usr/local/www/htdocs/mktg/prods.html</em>.  Mason loads and
executes that file as a component. In effect, Mason calls</p>
<pre>
    $m-&gt;comp('/mktg/prods.html', id=&gt;372)</pre>
<p>This component might in turn call other components and execute some Perl
code, or it might contain nothing more than static HTML.</p>
<p>
</p>
<h2><A NAME="dhandlers">dhandlers</a></h2>
<p>What happens when a user requests a component that doesn't exist? In
this case Mason scans backward through the URI, checking each
directory for a component named <em>dhandler</em> (``default handler'').  If
found, the dhandler is invoked and is expected to use
<code>$m-&gt;dhandler_arg</code> as the parameter to some
access function, perhaps a database lookup or location in another
filesystem. In a sense, dhandlers are similar in spirit to Perl's
AUTOLOAD feature; they are the ``component of last resort'' when a URL
points to a non-existent component.</p>
<p>Consider the following URL, in which <em>newsfeeds/</em> exists but not the
subdirectory <em>LocalNews</em> nor the component <em>Story1</em>:</p>
<pre>
    <a href="http://myserver/newsfeeds/LocalNews/Story1">http://myserver/newsfeeds/LocalNews/Story1</a></pre>
<p>In this case Mason constructs the following search path:</p>
<pre>
    /newsfeeds/LocalNews/Story1         =&gt; no such thing
    /newsfeeds/LocalNews/dhandler       =&gt; no such thing
    /newsfeeds/dhandler                 =&gt; found! (search ends)
    /dhandler</pre>
<p>The found dhandler would read ``LocalNews/Story1'' from
<code>$m-&gt;dhandler_arg</code> and use it as a retrieval key into a
database of stories.</p>
<p>Here's how a simple /newsfeeds/dhandler might look:</p>
<pre>
    &lt;&amp; header &amp;&gt;
    &lt;b&gt;&lt;% $headline %&gt;&lt;/b&gt;&lt;p&gt;
    &lt;% $body %&gt;
    &lt;&amp; footer &amp;&gt;</pre>
<pre>
    &lt;%init&gt;
    my $arg = $m-&gt;dhandler_arg;                # get rest of path
    my ($section, $story) = split(&quot;/&quot;, $arg);  # split out pieces
    my $sth = $DBH-&gt;prepare
        (qq{SELECT headline,body FROM news
            WHERE section = ? AND story = ?);
    $sth-&gt;execute($section, $story);
    my ($headline, $body) = $sth-&gt;fetchrow_array;
    return 404 if !$headline;                  # return &quot;not found&quot; if no such story
    &lt;/%init&gt;</pre>
<p>By default dhandlers do not get a chance to handle requests to a
directory itself (e.g. <em>/newsfeeds</em>). These are automatically
deferred to Apache, which generates an index page or a FORBIDDEN
error.  Often this is desirable, but if necessary the administrator
can let in directory requests as well; see the <A HREF="Admin.html#allowing_directory_requests">allowing directory requests</a> section of the administrator's manual.</p>
<p>A component or dhandler that does not want to handle a particular
request may defer control to the next dhandler by calling <code>&lt;
$m-</code>decline &gt;&gt;.</p>
<p>When using dhandlers under mod_perl, you may find that sometimes
Apache will not set a content type for a response.  This usually
happens when a dhandler handles a request for a non-existent file or
directory.  You can add a <code>&lt;Location&gt;</code> or <code>&lt;LocationMatch&gt;</code>
block containing a <code>SetType</code> directive to your Apache config file, or
you can just set the content type dynamically by calling <code>&lt;
$r-</code>content_type &gt;&gt;.</p>
<p>The administrator can customize the file name used for dhandlers with
the <A HREF="Params.html#dhandler_name">dhandler_name</a> parameter.</p>
<p>
</p>
<h2><A NAME="autohandlers">autohandlers</a></h2>
<p>Autohandlers allow you to grab control and perform some action just
before Mason calls the top-level component.  This might mean adding a
standard header and footer, applying an output filter, or setting up
global variables.</p>
<p>Autohandlers are directory based.  When Mason determines the top-level
component, it checks that directory and all parent directories for a
component called <em>autohandler</em>. If found, the autohandler is called
first.  After performing its actions, the autohandler typically calls
<code>$m-&gt;call_next</code> to transfer control to the original intended
component.</p>
<p><code>$m-&gt;call_next</code> works just like <code>$m-&gt;comp</code> except that the component path
and arguments are implicit. You can pass additional arguments to
<code>$m-&gt;call_next</code>; these are merged with the original arguments, taking
precedence in case of conflict.  This allows you, for example, to
override arguments passed in the URL.</p>
<p>Here is an autohandler that adds a common header and footer to each
page underneath its directory:</p>
<pre>
    &lt;html&gt;
    &lt;head&gt;&lt;title&gt;McHuffy Incorporated&lt;/title&gt;&lt;/head&gt;
    &lt;body style=&quot;background-color: pink&quot;&gt;</pre>
<pre>
    % $m-&gt;call_next;</pre>
<pre>
    &lt;hr /&gt;
    Copyright 1999 McHuffy Inc.
    &lt;/body&gt;
    &lt;/html&gt;</pre>
<p>Same idea, using components for the header/footer:</p>
<pre>
    &lt;&amp; /shared/header &amp;&gt;
    % $m-&gt;call_next;
    &lt;&amp; /shared/footer &amp;&gt;</pre>
<p>The next autohandler applies a filter to its pages, adding an absolute
hostname to relative image URLs:</p>
<pre>
    % $m-&gt;call_next;</pre>
<pre>
    &lt;%filter&gt;
    s{(&lt;img[^&gt;]+src=\&quot;)/} {$1http://images.mysite.com/}ig;
    &lt;/%filter&gt;</pre>
<p>Most of the time autohandler can simply call <code>$m-&gt;call_next</code>
without needing to know what the next component is. However, should
you need it, the component object is available from
<code>$m-&gt;fetch_next</code>. This is useful for calling the component manually,
e.g. if you want to suppress some original arguments or if you want to
use <code>$m-&gt;scomp</code> to store and process the output.</p>
<p>What happens if more than one autohandler applies to a page? Prior to
version 0.85, only the most specific autohandler would execute.  In
0.85 and beyond each autohandler gets a chance to run.  The top-most
autohandler runs first; each <code>$m-&gt;call_next</code> transfers control to the
next autohandler and finally to the originally called component. This
allows you, for example, to combine general site-wide templates and
more specific section-based templates.</p>
<p>Autohandlers can be made even more powerful in conjunction with
Mason's object-oriented style features: methods, attributes, and
inheritance.  In the interest of space these are discussed in a
separate section, <A HREF="#objectoriented_techniques">Object-Oriented Techniques</a>.</p>
<p>The administrator can customize the file name used for autohandlers
with the <A HREF="Params.html#autohandler_name">autohandler_name</a> parameter.</p>
<p>
</p>
<h2><A NAME="dhandlers_vs__autohandlers">dhandlers vs. autohandlers</a></h2>
<p>dhandlers and autohandlers both provide a way to exert control over a
large set of URLs. However, each specializes in a very different
application.  The key difference is that dhandlers are invoked only
when no appropriate component exists, while autohandlers are invoked
only in conjunction with a matching component.</p>
<p>As a rule of thumb: use an autohandler when you have a set of
components to handle your pages and you want to augment them
with a template/filter. Use a dhandler when you want to create a set
of ``virtual URLs'' that don't correspond to any actual components,
or to provide default behavior for a directory.</p>
<p>dhandlers and autohandlers can even be used in the same directory. For
example, you might have a mix of real URLs and virtual URLs to which
you would like to apply a common template/filter.</p>
<p>
</p>
<hr />
<h1><A NAME="passing_parameters">PASSING PARAMETERS</a></h1>
<p>This section describes Mason's facilities for passing parameters to
components (either from HTTP requests or component calls) and for
accessing parameter values inside components.</p>
<p>
</p>
<h2><A NAME="in_component_calls">In Component Calls</a></h2>
<p>Any Perl data type can be passed in a component call:</p>
<pre>
    &lt;&amp; /sales/header, s =&gt; 'dog', l =&gt; [2, 3, 4], h =&gt; {a =&gt; 7, b =&gt; 8} &amp;&gt;</pre>
<p>This command passes a scalar ($s), a list (@l), and a hash (%h). The
list and hash must be passed as references, but they will be automatically
dereferenced in the called component.</p>
<p>
</p>
<h2><A NAME="in_http_requests">In HTTP requests</a></h2>
<p>Consider a CGI-style URL with a query string:</p>
<pre>
    <a href="http://www.foo.com/mktg/prods.html?str=dog&amp;lst=2&amp;lst=3&amp;lst=4">http://www.foo.com/mktg/prods.html?str=dog&amp;lst=2&amp;lst=3&amp;lst=4</a></pre>
<p>or an HTTP request with some POST content. Mason automatically parses
the GET/POST values and makes them available to the component as
parameters.</p>
<p>
</p>
<h2><A NAME="accessing_parameters">Accessing Parameters</a></h2>
<p>Component parameters, whether they come from GET/POST or another
component, can be accessed in two ways.</p>
<p>1.  Declared named arguments: Components can define an
<code>&lt;%args&gt;</code> section listing argument names, types, and
default values. For example:</p>
<pre>
    &lt;%args&gt;
    $a
    @b       # a comment
    %c</pre>
<pre>
    # another comment
    $d =&gt; 5
    $e =&gt; $d*2
    @f =&gt; ('foo', 'baz')
    %g =&gt; (joe =&gt; 1, bob =&gt; 2)
    &lt;/%args&gt;</pre>
<p>Here, <em>$a</em>, <em>@b</em>, and <em>%c</em> are required arguments; the component generates
an error if the caller leaves them unspecified. <em>$d</em>, <em>$e</em>, <em>@f</em> and <em>%g</em> are
optional arguments; they are assigned the specified default values if
unspecified.  All the arguments are available as lexically scoped (``my'')
variables in the rest of the component.</p>
<p>Arguments are separated by one or more newlines. Comments may be used at
the end of a line or on their own line.</p>
<p>Default expressions are evaluated in top-to-bottom order, and one
expression may reference an earlier one (as $e references $d above).</p>
<p>Only valid Perl variable names may be used in <code>&lt;%args&gt;</code>
sections.  Parameters with non-valid variable names cannot be
pre-declared and must be fetched manually out of the %ARGS hash (see
below).  One common example of undeclarable parameters are the
``button.x/button.y'' parameters sent for a form submit.</p>
<p>2. %ARGS hash: This variable, always available, contains all of the
parameters passed to the component (whether or not they were
declared).  It is especially handy for dealing with large numbers of
parameters, dynamically named parameters, or parameters with non-valid
variable names. %ARGS can be used with or without an
<code>&lt;%args&gt;</code> section, and its contents are unrelated to what you
have declared in <code>&lt;%args&gt;</code>.</p>
<p>Here's how to pass all of a component's parameters to another component:</p>
<pre>
    &lt;&amp; template, %ARGS &amp;&gt;</pre>
<p>
</p>
<h2><A NAME="parameter_passing_examples">Parameter Passing Examples</a></h2>
<p>The following examples illustrate the different ways to pass and receive parameters.</p>
<p>1.  Passing a scalar <em>id</em> with value 5.</p>
<pre>
  In a URL: /my/URL?id=5
  In a component call: &lt;&amp; /my/comp, id =&gt; 5 &amp;&gt;
  In the called component, if there is a declared argument named...
    $id, then $id will equal 5
    @id, then @id will equal (5)
    %id, then an error occurs
  In addition, $ARGS{id} will equal 5.</pre>
<p>2.  Passing a list <em>colors</em> with values red, blue, and green.</p>
<pre>
  In a URL: /my/URL?colors=red&amp;colors=blue&amp;colors=green
  In an component call: &lt;&amp; /my/comp, colors =&gt; ['red', 'blue', 'green'] &amp;&gt;
  In the called component, if there is a declared argument named...
    $colors, then $colors will equal ['red', 'blue', 'green']
    @colors, then @colors will equal ('red', 'blue', 'green')
    %colors, then an error occurs
  In addition, $ARGS{colors} will equal ['red', 'blue', 'green'].</pre>
<p>3.  Passing a hash <em>grades</em> with pairs Alice =&gt; 92 and Bob =&gt; 87.</p>
<pre>
  In a URL: /my/URL?grades=Alice&amp;grades=92&amp;grades=Bob&amp;grades=87
  In an component call: &lt;&amp; /my/comp, grades =&gt; {Alice =&gt; 92, Bob =&gt; 87} &amp;&gt;
  In the called component, if there is a declared argument named...
    @grades, then @grades will equal ('Alice', 92, 'Bob', 87)
    %grades, then %grades will equal (Alice =&gt; 92, Bob =&gt; 87)
  In addition, $grade and $ARGS{grades} will equal
    ['Alice',92,'Bob',87] in the URL case, or {Alice =&gt; 92, Bob =&gt; 87}
    in the component call case.  (The discrepancy exists because, in a
    query string, there is no detectable difference between a list or
    hash.)</pre>
<p>
</p>
<h2><A NAME="using____instead">Using @_ instead</a></h2>
<p>If you don't like named parameters, you can pass a traditional
list of ordered parameters:</p>
<pre>
    &lt;&amp; /mktg/prods.html', 'dog', [2, 3, 4], {a =&gt; 7, b =&gt; 8} &amp;&gt;</pre>
<p>and access them as usual through Perl's @_ array:</p>
<pre>
    my ($scalar, $listref, $hashref) = @_;</pre>
<p>In this case no <code>&lt;%args&gt;</code> section is necessary.</p>
<p>We generally recommend named parameters for the benefits of
readability, syntax checking, and default value automation.  However
using <code>@_</code> may be convenient for very small components, especially
subcomponents created with <code>&lt;%def&gt;</code>.</p>
<p>Before Mason 1.21, @_ contained <em>copies</em> of the caller's arguments.
In Mason 1.21 and beyond, this unnecessary copying was eliminated and
@_ now contains <em>aliases</em> to the caller's arguments, just as with
regular Perl subroutines. For example, if a component updates $_[0],
the corresponding argument is updated (or an error occurs if it is not
updatable).</p>
<p>Most users won't notice this change because <code>&lt;%args&gt;</code> variables
and the <code>%ARGS</code> hash always contain copies of arguments.</p>
<p>See perlsub for more information on @_ aliasing.</p>
<p>
</p>
<hr />
<h1><A NAME="initialization_and_cleanup">INITIALIZATION AND CLEANUP</a></h1>
<p>The following sections contain blocks of Perl to execute at specific
times.</p>
<p>
</p>
<h2><A NAME="__init_">&lt;%init&gt;</a></h2>
<p>This section contains initialization code that executes as soon as the
component is called. For example: checking that a user is logged in;
selecting rows from a database into a list; parsing the contents of a
file into a data structure.</p>
<p>Technically an <code>&lt;%init&gt;</code> block is equivalent to a <code>&lt;%perl&gt;</code>
block at the beginning of the component. However, there is an
aesthetic advantage of placing this block at the end of the component
rather than the beginning.</p>
<p>We've found that the most readable components (especially for
non-programmers) contain HTML in one continuous block at the top, with
simple substitutions for dynamic elements but no distracting blocks of
Perl code.  At the bottom an <code>&lt;%init&gt;</code> block sets up the substitution
variables.  This organization allows non-programmers to work with the
HTML without getting distracted or discouraged by Perl code. For example:</p>
<pre>
    &lt;html&gt;
    &lt;head&gt;&lt;title&gt;&lt;% $headline %&gt;&lt;/title&gt;&lt;/head&gt;
    &lt;body&gt;
    &lt;h2&gt;&lt;% $headline %&gt;&lt;/h2&gt;
    &lt;p&gt;By &lt;% $author %&gt;, &lt;% $date %&gt;&lt;/p&gt;</pre>
<pre>
    &lt;% $body %&gt;</pre>
<pre>
    &lt;/body&gt;
    &lt;/html&gt;</pre>
<pre>
    &lt;%init&gt;
    # Fetch article from database
    my $dbh = DBI::connect ...;
    my $sth = $dbh-&gt;prepare(&quot;select * from articles where id = ?&quot;);
    $sth-&gt;execute($article_id);
    my ($headline, $date, $author, $body) = $sth-&gt;fetchrow_array;
    # Massage the fields
    $headline = uc($headline);
    my ($year, $month, $day) = split('-', $date);
    $date = &quot;$month/$day&quot;;
    &lt;/%init&gt;</pre>
<pre>
    &lt;%args&gt;
    $article_id
    &lt;/%args&gt;</pre>
<p>
</p>
<h2><A NAME="__cleanup_">&lt;%cleanup&gt;</a></h2>
<p>This section contains cleanup code that executes just before the
component exits. For example: closing a database connection or closing
a file handle.</p>
<p>A &lt;&lt; &lt;%cleanup&gt; &gt;&gt; block is equivalent to a <code>&lt;%perl&gt;</code> block at
the end of the component. This means it will NOT execute if the
component explicitly returns, or if an abort or error occurs in that
component or one of its children. Because of this limitation, and
because Perl is usually so good about cleaning up at the end of a
lexical scope (e.g. component), <code>&lt;%cleanup&gt;</code> sections are rarely
needed.</p>
<p>If you need code that is guaranteed to run when the component or
request exits, consider using a mod_perl cleanup handler, or creating
a custom class with a DESTROY method.</p>
<p>
</p>
<h2><A NAME="__once_">&lt;%once&gt;</a></h2>
<p>This code executes once when the component is loaded. Variables
declared in this section can be seen in all of a component's code and
persist for the lifetime of the component.</p>
<p>This section is useful for declaring persistent component-scoped
lexical variables (especially objects that are expensive to create),
declaring subroutines (both named and anonymous), and initializing
state.</p>
<p>This code does not run inside a request context. You cannot call
components or access <code>$m</code> or <code>$r</code> from this section. Also, do not
attempt to <code>return()</code> from a <code>&lt;%once&gt;</code> section; the current
compiler cannot properly handle it.</p>
<p>Normally this code will execute individually from every HTTP child
that uses the component. However, if the component is preloaded, this
code will only execute once in the parent.  Unless you have total control
over what components will be preloaded, it is safest to avoid
initializing variables that can't survive a fork(), e.g. DBI handles.
Use code like this to initialize such variables in the <code>&lt;%init&gt;</code>
section:</p>
<pre>
    &lt;%once&gt;
    my $dbh;      # declare but don't assign
    ...
    &lt;/%once&gt;</pre>
<pre>
    &lt;%init&gt;
    $dbh ||= DBI::connect ...
    ...
    &lt;/%init&gt;</pre>
<p>In addition, using <code>$m</code> or &lt;$r&gt; in this section will not work in a
preloaded component, because neither of those variable exist when a
component is preloaded.</p>
<p>
</p>
<h2><A NAME="__shared_">&lt;%shared&gt;</a></h2>
<p>As with <code>&lt;%once&gt;</code>, lexical (<code>my</code>) variables declared in this
section can be seen in all the rest of a component's code: the main
body, subcomponents, and methods.  However, unlike <code>&lt;%once&gt;</code>, the
code runs once per request (whenever the component is used) and its
variables last only until the end of the request.</p>
<p>A <code>&lt;%shared&gt;</code> section is useful for initializing variables needed in, say, the
main body and one more subcomponents or methods. See <A HREF="#objectoriented_techniques">Object-Oriented Techniques</a> for an example of usage.</p>
<p>It's important to realize that you do not have access to the <code>%ARGS</code>
hash or variables created via an <code>&lt;%args&gt;</code> block inside a shared
section.  However, you can access arguments via
<A HREF="Request.html#item_request_args">$m-&gt;request_args</a>.</p>
<p>Additionally, you cannot call a components' own methods or
subcomponents from inside a <code>&lt;%shared&gt;</code>, though you can call
other components.</p>
<p>Avoid using <code>&lt;%shared&gt;</code> for side-effect code that needs to run at a
predictable time during page generation. You may assume only that
<code>&lt;%shared&gt;</code> runs just before the first code that needs it and runs at
most once per request.</p>
<p>In the current implementation, the scope sharing is done with
closures, so variables will only be shared if they are visible at
compile-time in the other parts of the component.  In addition, you
can't rely on the specific destruction time of the shared variables,
because they may not be destroyed until the first time the <code>&lt;
&lt;%shared</code> &gt;&gt; section executes in a future request.  <code>&lt;%init&gt;</code>
offers a more predictable execution and destruction time.</p>
<p>Currently any component with a <code>&lt;%shared&gt;</code> section incurs an
extra performance penalty, because Mason must recreate its
anonymous subroutines the first time each new request uses the
component.  The exact penalty varies between systems and for most
applications will be unnoticeable. However, one should avoid using
<code>&lt;%shared&gt;</code> when patently unnecessary, e.g. when an <code>&lt;%init&gt;</code>
would work just as well.</p>
<p>Do not attempt to <code>return()</code> from a <code>&lt;%shared&gt;</code> section; the
current compiler cannot properly handle it.</p>
<p>
</p>
<hr />
<h1><A NAME="embedded_components">EMBEDDED COMPONENTS</a></h1>
<p>
</p>
<h2><A NAME="__def_name_">&lt;%def <em>name</em>&gt;</a></h2>
<p>Each instance of this section creates a <em>subcomponent</em> embedded
inside the current component. Inside you may place anything that a
regular component contains, with the exception of <code>&lt;%def&gt;</code>, <code>&lt;%method&gt;</code>,
<code>&lt;%once&gt;</code>, and <code>&lt;%shared&gt;</code> tags.</p>
<p>The <em>name</em> consists of characters in the set <code>[\w._-]</code>. To
call a subcomponent simply use its name in &lt;&amp; &amp;&gt; or <code>$m-&gt;comp</code>. A
subcomponent can only be seen from the surrounding component.</p>
<p>If you define a subcomponent with the same name as a file-based
component in the current directory, the subcomponent takes
precedence. You would need to use an absolute path to call the
file-based component. To avoid this situation and for general clarity,
we recommend that you pick a unique way to name all of your
subcomponents that is unlikely to interfere with file-based
components. A commonly accepted practice is to start subcomponent
names with ``.''.</p>
<p>While inside a subcomponent, you may use absolute or relative paths to
call file-based components and also call any of your ``sibling''
subcomponents.</p>
<p>The lexical scope of a subcomponent is separate from the main
component.  However a subcomponent can declare its own <code>&lt;%args&gt;</code> section
and have relevant values passed in.  You can also use a <code>&lt;%shared&gt;</code>
section to declare variables visible from both scopes.</p>
<p>In the following example, we create a ``.link'' subcomponent to produce a
standardized hyperlink:</p>
<pre>
    &lt;%def .link&gt;
    &lt;a href=&quot;<a href="http://www.&lt;%">http://www.&lt;%</a> $site %&gt;.com&quot;&gt;&lt;% $label %&gt;&lt;/a&gt;</pre>
<pre>
    &lt;%args&gt;
    $site
    $label=&gt;ucfirst($site)
    &lt;/%args&gt;
    &lt;/%def&gt;</pre>
<pre>
    Visit these sites:
    &lt;ul&gt;
     &lt;li&gt;&lt;&amp; .link, site=&gt;'yahoo' &amp;&gt;&lt;/li&gt;
     &lt;li&gt;&lt;&amp; .link, site=&gt;'cmp', label=&gt;'CMP Media' &amp;&gt;&lt;/li&gt;
     &lt;li&gt;&lt;&amp; .link, site=&gt;'excite' &amp;&gt;&lt;/li&gt;
    &lt;/ul&gt;</pre>
<p>
</p>
<h2><A NAME="__method_name_">&lt;%method <em>name</em>&gt;</a></h2>
<p>Each instance of this section creates a <em>method</em> embedded inside
the current component. Methods resemble subcomponents in terms of
naming, contents, and scope. However, while subcomponents can only be
seen from the parent component, methods are meant to be called from
other components.</p>
<p>There are two ways to call a method. First, via a path of the form
``comp:method'':</p>
<pre>
    &lt;&amp; /foo/bar:method1 &amp;&gt;</pre>
<pre>
    $m-&gt;comp('/foo/bar:method1');</pre>
<p>Second, via the call_method component method:</p>
<pre>
    my $comp = $m-&gt;fetch_comp('/foo/bar');
    ...
    $comp-&gt;call_method('method1');</pre>
<p>Methods are commonly used in conjunction with autohandlers to make
templates more flexible. See <A HREF="#objectoriented_techniques">Object-Oriented Techniques</a> for more information.</p>
<p>You cannot create a subcomponent and method with the same name. 
This is mostly to prevent obfuscation and accidental errors.</p>
<p>
</p>
<hr />
<h1><A NAME="flags_and_attributes">FLAGS AND ATTRIBUTES</a></h1>
<p>The <code>&lt;%flags&gt;</code> and <code>&lt;%attr&gt;</code> sections consist of key/value
pairs, one per line, joined by '=&gt;'.  In each pair, the key must be
any valid Perl ``bareword identifier'' (made of letters, numbers, and
the underscore character), and the value may be any scalar value,
including references.  An optional comment may follow each line.</p>
<p>
</p>
<h2><A NAME="__flags_">&lt;%flags&gt;</a></h2>
<p>Use this section to set official Mason flags that affect the current
component's behavior.</p>
<p>Currently there is only one flag, <code>inherit</code>, which specifies the
component's <em>parent</em> in the form of a relative or absolute component
path. A component inherits methods and attributes from its parent; see
<A HREF="#objectoriented_techniques">Object-Oriented Techniques</a> for
examples.</p>
<pre>
    &lt;%flags&gt;
    inherit=&gt;'/site_handler'
    &lt;/%flags&gt;</pre>
<p>
</p>
<h2><A NAME="__attr_">&lt;%attr&gt;</a></h2>
<p>Use this section to assign static key/value attributes that can be
queried from other components.</p>
<pre>
    &lt;%attr&gt;
    color =&gt; 'blue'
    fonts =&gt; [qw(arial geneva helvetica)]
    &lt;/%attr&gt;</pre>
<p>To query an attribute of a component, use the <code>attr</code> method:</p>
<pre>
    my $color = $comp-&gt;attr('color')</pre>
<p>where $comp is a component object.</p>
<p>Mason evaluates attribute values once when loading the component.
This makes them faster but less flexible than methods.</p>
<p>
</p>
<hr />
<h1><A NAME="filtering">FILTERING</a></h1>
<p>This section describes several ways to apply filtering functions over
the results of the current component.  By separating out and hiding a
filter that, say, changes HTML in a complex way, we allow
non-programmers to work in a cleaner HTML environment.</p>
<p>
</p>
<h2><A NAME="__filter__section">&lt;%filter&gt; section</a></h2>
<p>The <code>&lt;%filter&gt;</code> section allows you to arbitrarily filter the output of
the current component. Upon entry to this code, <code>$_</code> contains the
component output, and you are expected to modify it in place. The code
has access to component arguments and can invoke subroutines, call
other components, etc.</p>
<p>This simple filter converts the component output to UPPERCASE:</p>
<pre>
    &lt;%filter&gt;
    tr/a-z/A-Z/
    &lt;/%filter&gt;</pre>
<p>The following navigation bar uses a filter to ``unlink'' and highlight
the item corresponding to the current page:</p>
<pre>
    &lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt; | &lt;a href=&quot;/products/&quot;&gt;Products&lt;/a&gt; |
    &lt;a href=&quot;/bg.html&quot;&gt;Background&lt;/a&gt; | &lt;a href=&quot;/finance/&quot;&gt;Financials&lt;/a&gt; |
    &lt;a href=&quot;/support/&quot;&gt;Tech Support&lt;/a&gt; | &lt;a href=&quot;/contact.html&quot;&gt;Contact Us&lt;/a&gt;</pre>
<pre>
    &lt;%filter&gt;
    my $uri = $r-&gt;uri;
    s{&lt;a href=&quot;$uri/?&quot;&gt;(.*?)&lt;/a&gt;} {&lt;b&gt;$1&lt;/b&gt;}i;
    &lt;/%filter&gt;</pre>
<p>This allows a designer to code such a navigation bar intuitively
without <code>if</code> statements surrounding each link!  Note that the regular
expression need not be very robust as long as you have control over what
will appear in the body.</p>
<p>A filter block does not have access to variables declared in a
component's <code>&lt;%init&gt;</code> section, though variables declared in the
<code>&lt;%args&gt;</code>, <code>&lt;%once&gt;</code> or <code>&lt;%shared&gt;</code> blocks are
usable in a filter.</p>
<p>It should be noted that a filter cannot rely on receiving all of a
component's output at once, and so may be called multiple times with
different chunks of output.  This can happen if autoflush is on, or if
a filter-containing component, or the components it calls, call the
<code>$m-&gt;flush_buffer()</code> method.</p>
<p>You should never call Perl's <code>return()</code> function inside a filter
section, or you will not see any output at all.</p>
<p>You can use <A HREF="#component_calls_with_content">Component Calls with Content</a> if you want to filter specific parts of a component rather
than the entire component.</p>
<p>
</p>
<hr />
<h1><A NAME="comment_markers">COMMENT MARKERS</a></h1>
<p>There are several ways to place comments in components, i.e. arbitrary
text that is ignored by the parser.</p>
<p>
</p>
<h2><A NAME="__doc_">&lt;%doc&gt;</a></h2>
<p>Text in this section is treated as a comment and ignored. Most useful
for a component's main documentation.  One can easily write a program
to sift through a set of components and pull out their <code>&lt;%doc&gt;</code>
blocks to form a reference page.</p>
<p>
</p>
<h2><A NAME="_____comment______">&lt;% # comment... %&gt;</a></h2>
<p>A <code>&lt;% %&gt;</code> tag is considered a comment if all of its lines are
either whitespace, or begin with a '#' optionally preceded by
whitespace. For example,</p>
<pre>
    &lt;% # This is a single-line comment %&gt;</pre>
<pre>
    &lt;%
       # This is a
       # multi-line comment
    %&gt;</pre>
<p>
</p>
<h2><A NAME="___comment">%# comment</a></h2>
<p>Because a line beginning with <code>%</code> is treated as Perl, <code>%#</code>
automatically works as a comment. However we prefer the <code>&lt;% #
comment %&gt;</code> form over <code>%#</code>, because it stands out a little more
as a comment and because it is more flexible with regards to preceding
whitespace.</p>
<p>
</p>
<h2><A NAME="__if__0_____">% if (0) { }</a></h2>
<p>Anything between these two lines</p>
<pre>
   % if (0) {
   ...
   % }</pre>
<p>will be skipped by Mason, including component calls.  While we don't
recomend this for comments per se, it is a useful notation for
``commenting out'' code that you don't want to run.</p>
<p>
</p>
<h2><A NAME="html_xml_____comments">HTML/XML/... comments</a></h2>
<p>HTML and other markup languages will have their own comment markers, for example
<code>&lt;!-- --&gt;</code>. Note two important differences with these comments versus the
above comments:</p>
<ul>
<li>
<p>They will be sent to the client and appear in the source of the page.</p>
</li>
<li>
<p>They do not block component calls and other code from running,
so don't try to use them to comment out code!</p>
<pre>
   &lt;!-- Oops, the code below will still run
      &lt;&amp; /shared/expensive.mhtml &amp;&gt;
   --&gt;</pre>
</li>
</ul>
<p>
</p>
<hr />
<h1><A NAME="other_syntax">OTHER SYNTAX</a></h1>
<p>
</p>
<h2><A NAME="__text_">&lt;%text&gt;</a></h2>
<p>Text in this section is printed as-is with all Mason syntax ignored.
This is useful, for example, when documenting Mason itself from a
component:</p>
<pre>
    &lt;%text&gt;
    % This is an example of a Perl line.
    &lt;% This is an example of an expression block. %&gt;
    &lt;/%text&gt;</pre>
<p>This works for almost everything, but doesn't let you output
<code>&lt;/%text&gt;</code> itself! When all else fails, use <code>$m-&gt;print</code>:</p>
<pre>
    % $m-&gt;print('The tags are &lt;%text&gt; and &lt;/%text&gt;.');</pre>
<p>
</p>
<h2><A NAME="escaping_expressions">Escaping expressions</a></h2>
<p>Mason has facilities for <em>escaping</em> the output from <code>&lt;% %&gt;</code>
tags, on either a site-wide or a per-expression basis.</p>
<p>Any <code>&lt;% %&gt;</code> expression may be terminated by a '|' and one or more
escape flags (plus arbitrary whitespace), separated by commas:</p>
<pre>
    &lt;% $file_data |h %&gt;</pre>
<p>The current valid flags are:</p>
<ul>
<li><strong><A NAME="item_h">h</a></strong>

<p>Escape HTML ('&lt;' =&gt; '&amp;lt;', etc.) using <code>HTML::Entities::encode()</code>.
Before Perl 5.8.0 this module assumes that text is in the ISO-8859-1
character set; see <A HREF="Devel.html#userdefined_escapes">the next section</a> for how to override this escaping. After 5.8.0, the encoding
assumes that text is in Unicode.</p>
</li>
<li><strong><A NAME="item_u">u</a></strong>

<p>Escape a URL query string (':' =&gt; '%3A', etc.) - all but
[a-zA-Z0-9_.-]</p>
</li>
<li><strong><A NAME="item_n">n</a></strong>

<p>This is a special flag indicating that the default escape flags should
<em>not</em> be used for this substitution.</p>
</li>
</ul>
<p>The administrator may specify a set of default escape flags via the
<A HREF="Params.html#default_escape_flags">default_escape_flags</a> parameter. For example, if the administrator
sets <A HREF="Params.html#default_escape_flags">default_escape_flags</a> to <code>['h']</code>, then all &lt;% %&gt; expressions
will automatically be HTML-escaped.  In this case you would use the
<A HREF="#item_n"><code>n</code></a> flag to turn off HTML-escaping for a specific expression:</p>
<pre>
    &lt;% $html_block |n %&gt;</pre>
<p>Multiple escapes can be specified as a comma-separated list:</p>
<pre>
    &lt;% $uri | u, n %&gt;</pre>
<p>The old pre-defined escapes, 'h', 'u', and 'n', can be used <em>without</em>
commas, so that this is legal:</p>
<pre>
    &lt;% $uri | un %&gt;</pre>
<p>However, this only works for these three escapes, and no others.  If
you are using user-defined escapes as well, you <em>must</em> use a comma:</p>
<pre>
    &lt;% $uri | u, add_session %&gt;</pre>
<p>
</p>
<h3><A NAME="userdefined_escapes">User-defined Escapes</a></h3>
<p>Besides the default escapes mentioned above, it is possible for the
user to define their own escapes or to override the built-in 'h' and
'u' escapes.</p>
<p>This is done via the Interp object's <A HREF="Params.html#escape_flags">escape_flags</a> parameter or
<A HREF="Interp.html#item_set_escape">set_escape()</a> method.  Escape
names may be any number of characters as long as it matches the regex
<code>/^[\w-]+$/</code>.  The one exception is that you cannot override the 'n'
flag.</p>
<p>Each escape flag is associated with a subroutine reference.  The
subroutine should expect to receive a scalar reference, which should
be manipulated in place.  Any return value from this subroutine is
ignored.</p>
<p>Escapes can be defined at any time but using an escape that is not
defined will cause an error when executing that component.</p>
<p>A common use for this feature is to override the built-in HTML
escaping, which will not work with non-ISO-8559-1 encodings.  If
you are using such an encoding and want to switch the 'h' flag to do
escape just the minimal set of characters (<code>&lt;</code>, <code>&gt;</code>, <code>&amp;</code>,
<code>&quot;</code>), put this in your Apache configuration:</p>
<pre>
   PerlSetVar  MasonEscapeFlags  &quot;h =&gt; \&amp;HTML::Mason::Escapes::basic_html_escape&quot;</pre>
<p>Or, in a top-level autohandler:</p>
<pre>
    $m-&gt;interp-&gt;set_escape( h =&gt; \&amp;HTML::Mason::Escapes::basic_html_escape );</pre>
<p>Or you could write your own escape function for a particular encoding:</p>
<pre>
    $ah-&gt;interp-&gt;set_escape( h =&gt; \&amp;my_html_escape );</pre>
<p>And of course this can be used for all sorts of other things, like a
naughty words filter for the easily offended:</p>
<pre>
    $interp-&gt;set_escape( 'no-naughty' =&gt; \&amp;remove_naughty_words );</pre>
<p>
</p>
<h3><A NAME="manually_applying_escapes">Manually applying escapes</a></h3>
<p>You can manually apply one or more escapes to text using the <A HREF="Interp.html#item_apply_escapes">Interp object's <code>apply_escapes()</code> method</a>. e.g.</p>
<pre>
    $m-&gt;interp-&gt;apply_escapes( 'some html content', 'h' );</pre>
<p>
</p>
<h2><A NAME="backslash_at_end_of_line">Backslash at end of line</a></h2>
<p>A backslash (\) at the end of a line suppresses the newline. In HTML
components, this is mostly useful for fixed width areas like <code>&lt;pre&gt;</code>
tags, since browsers ignore white space for the most part. An example:</p>
<pre>
    &lt;pre&gt;
    foo
    % if (1) {
    bar
    % }
    baz
    &lt;/pre&gt;</pre>
<p>outputs</p>
<pre>
    foo
    bar
    baz</pre>
<p>because of the newlines on lines 2 and 4. (Lines 3 and 5 do not
generate a newline because the entire line is taken by Perl.)
To suppress the newlines:</p>
<pre>
    &lt;pre&gt;
    foo\
    % if (1) {
    bar\
    % }
    baz
    &lt;/pre&gt;</pre>
<p>which prints</p>
<pre>
    foobarbaz</pre>
<p>
</p>
<hr />
<h1><A NAME="data_caching">DATA CACHING</a></h1>
<p>Mason's data caching interface allows components to cache the results
of computation for improved performance.  Anything may be cached, from
a block of HTML to a complex data structure.</p>
<p>Each component gets its own private, persistent data cache. Except
under special circumstances, one component does not access another
component's cache. Each cached value may be set to expire at a certain
time.</p>
<p>Data caching is implemented on top of one of two external caching
APIs: <code>Cache::Cache</code> or its newer sibling <code>CHI</code>. You control which
one Mason uses with the <A HREF="Params.html#data_cache_api">data_cache_api</a> parameter. Currently
<code>Cache::Cache</code> is the default, but we will switch to <code>CHI</code> once it
is more mature.  The APIs are very similar for Mason users, so that
most of the information below applies to both; any differences are
noted.</p>
<p>
</p>
<h2><A NAME="basic_usage">Basic Usage</a></h2>
<p>The <code>$m-&gt;cache</code> method returns a cache object representing the cache for
this component. Here's the typical usage of <code>$m-&gt;cache</code>:</p>
<pre>
    my $result = $m-&gt;cache-&gt;get('key');
    if (!defined($result)) {
        ... compute $result ...
        $m-&gt;cache-&gt;set('key', $result);
    }</pre>
<p><code>$m-&gt;cache-&gt;get</code> attempts to retrieve this component's cache
value. If the value is available it is placed in <code>$result</code>. If the
value is not available, <code>$result</code> is computed and stored in the
cache by <code>$m-&gt;cache-&gt;set</code>.</p>
<p>
</p>
<h2><A NAME="multiple_keys_values">Multiple Keys/Values</a></h2>
<p>A cache can store multiple key/value pairs. A value can be
anything serializable by <code>Storable</code>, from a simple scalar to an
arbitrary complex list or hash reference:</p>
<pre>
    $m-&gt;cache-&gt;set(name =&gt; $string);
    $m-&gt;cache-&gt;set(friends =&gt; \@list);
    $m-&gt;cache-&gt;set(map =&gt; \%hash);</pre>
<p>You can fetch all the keys in a cache with</p>
<pre>
    my @idents = $m-&gt;cache-&gt;get_keys;</pre>
<p>It should be noted that Mason reserves all keys beginning with
<code>__mason</code> for its own use.</p>
<p>
</p>
<h2><A NAME="expiration">Expiration</a></h2>
<p>You can pass an optional third argument to <code>$m-&gt;cache-&gt;set</code>
indicating when the item should expire:</p>
<pre>
    $m-&gt;cache-&gt;set('name1', $string1, '5 min');  # Expire in 5 minutes
    $m-&gt;cache-&gt;set('name2', $string2, '3h');     # Expire in 3 hours</pre>
<p>To change the expiration time for a piece of data, call <code>set</code> again
with the new expiration. To expire an item immediately, use
<code>$m-&gt;cache-&gt;remove</code>.</p>
<p>You can also specify an expiration condition when you fetch the item,
using the <em>expire_if</em> option:</p>
<pre>
    my $result = $m-&gt;cache-&gt;get('key',
        expire_if=&gt;sub { $_[0]-&gt;get_created_at &lt; (stat($file))[9] });</pre>
<p><em>expire_if</em> takes an anonymous subroutine, which is called with the
<A HREF="#cache_object">cache object</a> as its only parameter. If the
subroutine returns a true value, the item is expired. In the example
above, we expire the item whenever a certain file changes.</p>
<p>Finally, you can expire a cache item from an external script; see
<A HREF="#accessing_a_cache_externally">Accessing a Cache Externally</a> below.</p>
<p>
</p>
<h2><A NAME="avoiding_concurrent_recomputatio">Avoiding Concurrent Recomputation</a></h2>
<p>The code shown in ``Basic Usage'' above,</p>
<pre>
   my $result = $m-&gt;cache-&gt;get('key');
   if (!defined($result)) {
       ... compute $result ...
       $m-&gt;cache-&gt;set('key', $result);
   }</pre>
<p>can suffer from a kind of race condition for caches that
are accessed frequently and take a long time to recompute.</p>
<p>Suppose that a particular cache value is accessed five times a
second and takes three seconds to recompute.  When the cache expires,
the first process comes in, sees that it is expired, and starts to
recompute the value.  The second process comes in and does the same thing.
This sequence continues until the first process finishes and stores
the new value.  On average, the value will be recomputed and written
to the cache 15 times!</p>
<p>One solution is the <em>busy_lock</em> flag:</p>
<pre>
   my $result = $m-&gt;cache-&gt;get('key', busy_lock=&gt;'30 sec');</pre>
<p>In this case, when the value cannot be retrieved, <code>get()</code> sets
the expiration time of the value 30 seconds in the future before
returning <code>undef</code>.  This tells the first process to compute the new
value while causing subsequent processes to use the old value for 30
seconds.</p>
<p>Should the 30 seconds expire before the first process is done, a second
process will start computing the new value while setting the expiration
time yet another 30 seconds in the future, and so on.</p>
<p>The disadvantage of this solution is that multiple writes to the cache
will be performed for each <code>set()</code>.</p>
<p>Another solution, available only if you are using <code>CHI</code>, is
<code>expires_variance</code> which will create a variable time window during
which expiration may occur. See the <code>CHI</code> documentation for details.</p>
<p>
</p>
<h2><A NAME="caching_all_output">Caching All Output</a></h2>
<p>Occasionally you will need to cache the complete output of a
component.  For this purpose, Mason offers the <code>$m-&gt;cache_self</code>
method.  This method causes Mason to check to see if this component
has already been run and its output cached.  If this is the case, this
output is simply sent as output.  Otherwise, the component run
normally and its output and return value cached.</p>
<p>It is typically used right at the top of an <code>&lt;%init&gt;</code> section:</p>
<pre>
    &lt;%init&gt;
    return if $m-&gt;cache_self(key =&gt; 'fookey', expires_in =&gt; '3 hours',
                             ... &lt;other cache options&gt; ...);
     ... &lt;rest of init&gt; ...
    &lt;/%init&gt;</pre>
<p>A full list of parameters and examples are available in the
<A HREF="Request.html#item_cache_self">cache_self</a> section of the Request
manual.</p>
<p>
</p>
<h2><A NAME="cache_object">Cache Object</a></h2>
<p><code>$m-&gt;cache-&gt;get_object</code> returns a <code>Cache::Object</code> or
<code>CHI::CacheObject</code> associated with a particular key. You can use this
to retrieve useful meta-data:</p>
<pre>
    my $co = $m-&gt;cache-&gt;get_object('name1');
    $co-&gt;get_created_at();    # when was object stored in cache
    $co-&gt;get_expires_at();    # when does object expire</pre>
<p>
</p>
<h2><A NAME="choosing_a_cache_subclass__with_">Choosing a Cache Subclass - with Cache::Cache</a></h2>
<p>The <code>Cache::Cache</code> API is implemented by a variety of backend subclasses. For
example, <code>FileCache</code> implements the interface with a set of
directories and files, <code>MemoryCache</code> implements the interface in
process memory, and <code>SharedMemoryCache</code> implements the interface in
shared memory.</p>
<p>By default <code>$m-&gt;cache</code> uses <code>FileCache</code>, but you can override
this with the <em>cache_class</em> keyword. The value must be the name of a
<code>Cache::Cache</code> subclass; the prefix ``Cache::'' need not be included.
For example:</p>
<pre>
    my $result = $m-&gt;cache(cache_class =&gt; 'MemoryCache')-&gt;get('key');
    $m-&gt;cache(cache_class =&gt; 'MemoryCache')-&gt;set(key =&gt; $result);</pre>
<p>You can even specify different subclasses for different keys in the
same component. Just make sure the correct value is passed to all
calls to <code>$m-&gt;cache</code>; Mason does not remember which subclass you
have used for a given component or key.</p>
<p>The administrator can set the default cache subclass used by all
components with the <A HREF="Params.html#data_cache_defaults">data_cache_defaults</a> parameter.</p>
<p>
</p>
<h2><A NAME="choosing_a_cache_subclass__with_">Choosing a Cache Subclass - with CHI</a></h2>
<p>The <code>CHI</code> API is implemented by a variety of drivers, for example
<code>CHI::Driver::File</code>, <code>CHI::Driver::FastMmap</code>, and
<code>CHI::Driver::Memcached</code>.</p>
<p><code>CHI::Driver::File</code> is the default, but you can override this with
the <em>driver</em> keyword. The value must be the name of a <code>CHI::Driver</code>
subclass; the prefix ``CHI::Driver::'' need not be included.  For
example:</p>
<pre>
    my $cache = $m-&gt;cache(driver =&gt; 'Memcached', servers =&gt; [ ... ]);
    my $result = $cache-&gt;get('key');
    $cache-&gt;set(key =&gt; $result);</pre>
<p>You can even specify different subclasses for different keys in the
same component. Just make sure the correct value is passed to all
calls to <code>$m-&gt;cache</code>; Mason does not remember which subclass you
have used for a given component or key.</p>
<p>The administrator can set the default cache subclass used by all
components with the <A HREF="Params.html#data_cache_defaults">data_cache_defaults</a> parameter.</p>
<p>
</p>
<h2><A NAME="accessing_a_cache_externally">Accessing a Cache Externally</a></h2>
<p>To access a component's cache from outside the component (e.g. in an
external Perl script), you'll need have the following information:</p>
<ul>
<li>
<p>the namespace associated with the component. For <code>Cache::Cache</code>, the function
<code>HTML::Mason::Utils::data_cache_namespace</code>,
given a component id (usually just the component path), returns the
namespace. For <code>CHI</code>, the component id/path itself is the namespace.</p>
</li>
<li>
<p>the cache_root, for file-based caches only. Defaults to the
``cache'' subdirectory under the Mason data directory.</p>
</li>
</ul>
<p>Given this information you can get a handle on the component's cache.
For example, the following code removes a cache item for component
<em>/foo/bar</em>, assuming the data directory is <em>/usr/local/www/mason</em>
and you are using the default file backend:</p>
<pre>
    use HTML::Mason::Utils qw(data_cache_namespace);</pre>
<pre>
    # With Cache::Cache
    my $cache = new Cache::FileCache
        ( { namespace =&gt; data_cache_namespace(&quot;/foo/bar&quot;),
            cache_root =&gt; &quot;/usr/local/www/mason/cache&quot; } );</pre>
<pre>
    # With CHI
    my $cache = CHI-&gt;new
        ( driver =&gt; 'File',
          namespace =&gt; &quot;/foo/bar&quot;,
          cache_root =&gt; &quot;/usr/local/www/mason/cache&quot; );</pre>
<pre>
    # Remove one key
    $cache-&gt;remove('key1');</pre>
<pre>
    # Remove all keys
    $cache-&gt;clear;</pre>
<p>
</p>
<h2><A NAME="mason_1_0x_cache_api">Mason 1.0x Cache API</a></h2>
<p>For users upgrading from 1.0x and earlier, any existing $m-&gt;cache
code will be incompatible with the new API. However, if you wish to
continue using the 1.0x cache API for a while, you (or your
administrator) can set <A HREF="Params.html#data_cache_api">data_cache_api</a> to '1.0'. All of the
$m-&gt;cache options with the exception of <code>tie_class</code> should be
supported.</p>
<p>The <code>access_data_cache</code> function is no longer available; this will
need to be converted to use <code>Cache::Cache</code> directly, as described in
the <A HREF="Devel.html#accessing_a_cache_externally">previous section</a>.</p>
<p>
</p>
<hr />
<h1><A NAME="webspecific_features">WEB-SPECIFIC FEATURES</a></h1>
<p>
</p>
<h2><A NAME="sending_http_headers">Sending HTTP Headers</a></h2>
<p>Mason automatically sends HTTP headers via <code>$r-&gt;send_http_header</code>
but it will not send headers if they've already been sent manually.</p>
<p>To determine the exact header behavior on your system, you need to
know whether your server's default is to have <A HREF="Params.html#autoflush">autoflush</a> on or off.
Your administrator should have this information.  If your administrator
doesn't know then it is probably off, the default.</p>
<p>With autoflush off the header situation is extremely simple: Mason
waits until the very end of the request to send headers. Any component
can modify or augment the headers.</p>
<p>With autoflush on the header situation is more complex.  Mason will
send headers just before sending the first output.  This means that if
you want to affect the headers with autoflush on, you must do so
before any component sends any output.  Generally this takes place in
an <code>&lt;%init&gt;</code> section.</p>
<p>For example, the following top-level component calls another component
to see whether the user has a cookie; if not, it inserts a new cookie
into the header.</p>
<pre>
    &lt;%init&gt;
    my $cookie = $m-&gt;comp('/shared/get_user_cookie');
    if (!$cookie) {
        $cookie = new CGI::Cookie (...);
        $r-&gt;header_out('Set-cookie' =&gt; $cookie);
    }
    ...
    &lt;/%init&gt;</pre>
<p>With autoflush off this code will always work.  Turn autoflush on and
this code will only work as long as <em>/shared/get_user_cookie</em> doesn't
output anything (given its functional nature, it shouldn't).</p>
<p>The administrator can turn off automatic header sending via the
<A HREF="Params.html#auto_send_headers">auto_send_headers</a> parameter. You can also turn it off on
individual pages with</p>
<pre>
    $m-&gt;auto_send_headers(0);</pre>
<p>
</p>
<h2><A NAME="returning_http_status">Returning HTTP Status</a></h2>
<p>The value returned from the top-most component becomes the status code
of the request. If no value is explicitly returned, it defaults to OK
(0).</p>
<p>Simply returning an error status (such as 404) from the top-most
component has two problems in practice. First, the decision to return
an error status often resides further down in the component
stack. Second, you may have generated some content by the time this
decision is made. (Both of these are more likely to be true when using
autohandlers.)</p>
<p>Thus the safer way to generate an error status is</p>
<pre>
   $m-&gt;clear_buffer;
   $m-&gt;abort($status);</pre>
<p><code>$m-&gt;abort</code> bypasses the component stack and ensures that
<code>$status</code> is returned from the top-most component. It works by
throwing an exception. If you wrapped this code (directly or
indirectly) in an eval, you must take care to rethrow the exception,
or the status will not make it out:</p>
<pre>
   eval { $m-&gt;comp('...') };
   if (my $err = $@) {
      if ($m-&gt;aborted) {
          die $err;
      } else {
          # deal with non-abort exceptions
      }
   }</pre>
<p>
</p>
<h3><A NAME="filters_and__m_abort">Filters and $m-&gt;abort</a></h3>
<p>A filter section will still be called after a component aborts with
<code>$m-&gt;abort</code>.  You can always check <code>$m-&gt;aborted</code> in your
<code>&lt;%filter&gt;</code> block if you don't want to run the filter after an abort.</p>
<pre>
  &lt;%filter&gt;
  unless ( $m-&gt;aborted ) {
      $_ .= ' filter stuff';
  }
  &lt;/%filter&gt;</pre>
<p>
</p>
<h2><A NAME="external_redirects">External Redirects</a></h2>
<p>Because it is so commonly needed, Mason 1.1x and on provides an
external redirect method:</p>
<pre>
    $m-&gt;redirect($url);    # Redirects with 302 status</pre>
<p>This method uses the clear_buffer/abort technique mentioned above,
so the same warnings apply regarding evals.</p>
<p>Also, if you generate any output <em>after</em> calling <code>$m-&gt;redirect</code>,
then this output will be sent, and will break the redirect.  For
example:</p>
<pre>
  % eval { $m-&gt;comp('redirect', ...) };</pre>
<pre>
  % die $@ if $@;</pre>
<p>The blank line between the two Perl lines is new output generated
after the redirect.  Either remove it or call <code>$m-&gt;clear_buffer</code>
immediately before calling <code>die()</code>.</p>
<p>
</p>
<h2><A NAME="internal_redirects">Internal Redirects</a></h2>
<p>There are two ways to perform redirects that are invisible to the
client.</p>
<p>First, you can use a Mason subrequest (see <A HREF="#subrequests">Subrequests</a>). This only
works if you are redirecting to another Mason page.</p>
<p>Second, you can use Apache's internal_redirect method, which works
whether or not the new URL will be handled by Mason.  Use it this way:</p>
<pre>
    $r-&gt;internal_redirect($url);
    $m-&gt;auto_send_headers(0);
    $m-&gt;clear_buffer;
    $m-&gt;abort;</pre>
<p>The last three lines prevent the original request from accidentally
generating extra headers or content.</p>
<p>
</p>
<hr />
<h1><A NAME="using_the_perl_debugger">USING THE PERL DEBUGGER</a></h1>
<p>You can use the perl debugger in conjunction with a live
mod_perl/Mason server with the help of Apache::DB, available from
CPAN. Refer to the Apache::DB documentation for details.</p>
<p>The only tricky thing about debugging Mason pages is that components
are implemented by anonymous subroutines, which are not easily
breakpoint'able. To remedy this, Mason calls the dummy subroutine
<code>debug_hook</code> at the beginning of each component. You can breakpoint
this subroutine like so:</p>
<pre>
    b HTML::Mason::Request::debug_hook</pre>
<p>debug_hook is called with two parameters: the current Request object
and the full component path. Thus you can breakpoint specific
components using a conditional on $_[1]:</p>
<pre>
    b HTML::Mason::Request::debug_hook $_[1] =~ /component name/</pre>
<p>You can avoid all that typing by adding the following to your
~/.perldb file:</p>
<pre>
    # Perl debugger aliases for Mason
    $DB::alias{mb} = 's/^mb\b/b HTML::Mason::Request::debug_hook/';</pre>
<p>which reduces the previous examples to just:</p>
<pre>
    mb
    mb $_[1] =~ /component name/</pre>
<p>Mason normally inserts '#line' directives into compiled components so
that line numbers are reported relative to the source file. Depending
on your task, this can be a help or a hindrance when using the
debugger.  The administrator can turn off '#line' directives with
the <A HREF="Params.html#use_source_line_numbers">use_source_line_numbers</a> parameter.</p>
<p>
</p>
<hr />
<h1><A NAME="objectoriented_techniques">OBJECT-ORIENTED TECHNIQUES</a></h1>
<p>Earlier you learned how to assign a common template to an entire
hierarchy of pages using <em>autohandlers</em>. The basic template looks like:</p>
<pre>
    header HTML
    % $m-&gt;call_next;
    footer HTML</pre>
<p>However, sometimes you'll want a more flexible template that adjusts
to the requested page.  You might want to allow each page or
subsection to specify a title, background color, or logo image while
leaving the rest of the template intact. You might want some pages or
subsections to use a different template, or to ignore templates
entirely.</p>
<p>These issues can be addressed with the object-oriented style
primitives introduced in Mason 0.85.</p>
<p>Note: we use the term object-oriented loosely. Mason borrows concepts
like inheritance, methods, and attributes from object methodology but
implements them in a shallow way to solve a particular set of
problems. Future redesigns may incorporate a deeper object
architecture if the current prototype proves successful.</p>
<p>
</p>
<h2><A NAME="determining_inheritance">Determining inheritance</a></h2>
<p>Every component may have a single <em>parent</em>. The default parent is a
component named <code>autohandler</code> in the closest parent directory.  This
rule applies to autohandlers too: an autohandler may not have itself
as a parent but may have an autohandler further up the tree as its
parent.</p>
<p>You can use the <code>inherit</code> flag to override a component's parent:</p>
<pre>
    &lt;%flags&gt;
    inherit =&gt; '/foo/bar'
    &lt;/%flags&gt;</pre>
<p>If you specify undef as the parent, then the component inherits from
no one.  This is how to suppress templates.</p>
<p>Currently there is no way to specify a parent dynamically at run-time,
or to specify multiple parents.</p>
<p>
</p>
<h2><A NAME="content_wrapping">Content wrapping</a></h2>
<p>At page execution time, Mason builds a chain of components from the
called component, its parent, its parent's parent, and so
on. Execution begins with the top-most component; calling
<code>$m-&gt;call_next</code> passes control to the next component in the chain.  This
is the familiar autohandler ``wrapping'' behavior, generalized for any
number of arbitrarily named templates.</p>
<p>
</p>
<h2><A NAME="accessing_methods_and_attributes">Accessing methods and attributes</a></h2>
<p>A template can access methods and/or attributes of the requested
page. First, use <code>$m-&gt;request_comp</code> to get a handle on the
appropriate component:</p>
<pre>
    my $self = $m-&gt;request_comp;</pre>
<p>$self now refers to the component corresponding to the requested page
(the component at the end of the chain).</p>
<p>To access a method for the page, use <code>call_method</code>:</p>
<pre>
    $self-&gt;call_method('header');</pre>
<p>This looks for a method named 'header' in the page component.  If no
such method exists, the chain of parents is searched upwards, until
ultimately a ``method not found'' error occurs. Use 'method_exists' to
avoid this error for questionable method calls:</p>
<pre>
    if ($self-&gt;method_exists('header')) { ...</pre>
<p>The component returned by the <code>$m-&gt;request_comp</code> method never
changes during request execution.  In contrast, the component returned
by <code>$m-&gt;base_comp</code> may change several times during request
execution.</p>
<p>When execution starts, the base component is the same as the requested
component.  Whenever a component call is executed, the base component
may become the component that was called.  The base component will
change for all component calls <strong>except</strong> in the following cases:</p>
<ul>
<li>
<p>A component is called via its component object rather than its path,
for example:</p>
<pre>
  &lt;&amp; $m-&gt;fetch_comp('/some/comp'), foo =&gt; 1 &amp;&gt;</pre>
</li>
<li>
<p>A subcomponent (defined with <code>&lt;%def&gt;</code>) is called.</p>
</li>
<li>
<p>A method is called via the use of <code>SELF:</code>, <code>PARENT:</code>, or
<code>REQUEST:</code>.  These are covered in more detail below.</p>
</li>
</ul>
<p>In all other cases, the base component is the called component or the
called component's owner component if that called component is a
method.</p>
<p>As hinted at above, Mason provides a shortcut syntax for method calls.</p>
<p>If a component call path starts with <code>SELF:</code>, then Mason will start
looking for the method (the portion of the call after <code>SELF:</code>), in
the base component.</p>
<pre>
    &lt;&amp; SELF:header &amp;&gt;
    $m-&gt;comp('SELF:header')</pre>
<p>If the call path starts with <code>PARENT:</code>, then Mason will start looking
in the current component's parent for the named method.</p>
<pre>
    &lt;&amp; PARENT:header &amp;&gt;
    $m-&gt;comp('PARENT:header')</pre>
<p>In the context of a component path, PARENT is shorthand for
<code>$m-&gt;current_comp-&gt;parent</code>.</p>
<p>If the call path begins with <code>REQUEST:</code>, then Mason looks for the
method in the requested component.  REQUEST is shorthand for <code>&lt;
$m-</code>request_comp &gt;&gt;.</p>
<p>The rules for attributes are similar. To access an attribute for the
page, use <code>attr</code>:</p>
<pre>
    my $color = $self-&gt;attr('color')</pre>
<p>This looks for an attribute named 'color' in the $self component. If
no such attribute exists, the chain of parents is searched upwards,
until ultimately an ``attribute not found'' error occurs. Use
<code>attr_exists</code> or <code>attr_if_exist</code> to avoid this error for
questionable attributes:</p>
<pre>
    if ($self-&gt;attr_exists('color')) { ...</pre>
<pre>
    my $color = $self-&gt;attr_if_exists('color'); # if it doesn't exist $color is undef</pre>
<p>
</p>
<h2><A NAME="sharing_data">Sharing data</a></h2>
<p>A component's main body and its methods occupy separate lexical
scopes. Variables declared, say, in the <code>&lt;%init&gt;</code> section of the main
component cannot be seen from methods.</p>
<p>To share variables, declare them either in the <code>&lt;%once&gt;</code> or <code>&lt;%shared&gt;</code>
section. Both sections have an all-inclusive scope. The <code>&lt;%once&gt;</code>
section runs once when the component loads; its variables are
persistent for the lifetime of the component. The <code>&lt;%shared&gt;</code> section
runs once per request (when needed), just before any code in the
component runs; its variables last only til the end of the request.</p>
<p>In the following example, various sections of code require information
about the logged-in user. We use a <code>&lt;%shared&gt;</code> section to fetch these
in a single request.</p>
<pre>
    &lt;%attr&gt;
    title=&gt;sub { &quot;Account for $full_name&quot; }
    &lt;/%attr&gt;</pre>
<pre>
    &lt;%method lefttoc&gt;
    &lt;i&gt;&lt;% $full_name %&gt;&lt;/i&gt;
    (&lt;a href=&quot;logout.html&quot;&gt;Log out&lt;/a&gt;)&lt;br /&gt;
    ...
    &lt;/%method&gt;</pre>
<pre>
    Welcome, &lt;% $fname %&gt;. Here are your options:</pre>
<pre>
    &lt;%shared&gt;
    my $dbh = DBI::connect ...;
    my $user = $r-&gt;connection-&gt;user;
    my $sth = $dbh-&gt;prepare(&quot;select lname,fname, from users where user_id = ?&quot;);
    $sth-&gt;execute($user);
    my ($lname, $fname) = $sth-&gt;fetchrow_array;
    my $full_name = &quot;$first $last&quot;;
    &lt;/%shared&gt;</pre>
<p><code>&lt;%shared&gt;</code> presents a good alternative to <code>&lt;%init&gt;</code> when data is needed
across multiple scopes. Outside these situations, <code>&lt;%init&gt;</code> is preferred
for its slightly greater speed and predictable execution model.</p>
<p>
</p>
<h2><A NAME="example">Example</a></h2>
<p>Let's say we have three components:</p>
<pre>
    /autohandler
    /products/autohandler
    /products/index.html</pre>
<p>and that a request comes in for /products/index.html.</p>
<p><em>/autohandler</em> contains a general template for the site, referring to a
number of standard methods and attributes for each page:</p>
<pre>
    &lt;head&gt;
    &lt;title&gt;&lt;&amp; SELF:title &amp;&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body style=&quot;&lt;% $self-&gt;attr('body_style') %&gt;&quot;&gt;
    &lt;&amp; SELF:header &amp;&gt;</pre>
<pre>
    &lt;div id=&quot;main&quot;&gt;
    % $m-&gt;call_next;
    &lt;/div&gt;</pre>
<pre>
    &lt;&amp; SELF:footer &amp;&gt;
    &lt;/body&gt;</pre>
<pre>
    &lt;%init&gt;
    my $self = $m-&gt;base_comp;
    ...
    &lt;/%init&gt;</pre>
<pre>
    &lt;%attr&gt;
    body_style =&gt; 'standard'
    &lt;/%attr&gt;</pre>
<pre>
    &lt;%method title&gt;
    McGuffey Inc.
    &lt;/%method&gt;</pre>
<pre>
    &lt;%method header&gt;
    &lt;h2&gt;&lt;&amp; SELF:title &amp;&gt;&lt;/h2&gt;
    &lt;/%method&gt;</pre>
<pre>
    &lt;%method footer&gt;
    &lt;/%method&gt;</pre>
<p>Notice how we provide defaults for each method and attribute, even if blank.</p>
<p><em>/products/autohandler</em> overrides some attributes and methods for the
<em>/products</em> section of the site.</p>
<pre>
    &lt;%attr&gt;
    body_style =&gt; 'plain'
    &lt;/%attr&gt;
    &lt;%method title&gt;
    McGuffey Inc.: Products
    &lt;/%method&gt;</pre>
<pre>
    % $m-&gt;call_next;</pre>
<p>Note that this component, though it only defines attributes and
methods, must call <code>$m-&gt;call_next</code> if it wants the rest of the
chain to run.</p>
<p><em>/products/index.html</em> might override a few attributes, but mainly provides
a primary section for the body.</p>
<p>
</p>
<hr />
<h1><A NAME="common_traps">COMMON TRAPS</a></h1>
<dl>
<dt><strong><A NAME="item_content">Do not call $r-&gt;content or ``new CGI''</a></strong>

<dd>
<p>Mason calls <A HREF="#item_content"><code>$r-&gt;content</code></a> itself to read request input, emptying
the input buffer and leaving a trap for the unwary: subsequent calls
to <A HREF="#item_content"><code>$r-&gt;content</code></a> hang the server. This is a mod_perl ``feature'' that
may be fixed in an upcoming release.</p>
</dd>
<dd>
<p>For the same reason you should not create a CGI object like</p>
</dd>
<dd>
<pre>
  my $query = new CGI;</pre>
</dd>
<dd>
<p>when handling a POST; the CGI module will try to reread request input
and hang. Instead, create an empty object:</p>
</dd>
<dd>
<pre>
  my $query = new CGI (&quot;&quot;);</pre>
</dd>
<dd>
<p>such an object can still be used for all of CGI's useful HTML output
functions. Or, if you really want to use CGI's input functions,
initialize the object from %ARGS:</p>
</dd>
<dd>
<pre>
  my $query = new CGI (\%ARGS);</pre>
</dd>
</li>
</dl>
<p>
</p>
<hr />
<h1><A NAME="mason_and_source_filters">MASON AND SOURCE FILTERS</a></h1>
<p>Modules which work as source filters, such as <code>Switch.pm</code>, will only
work when you are using object files.  This is because of how source
filters are implemented, and cannot be changed by the Mason authors.</p>
<p>
</p>
<hr />
<h1><A NAME="authors">AUTHORS</a></h1>
<p>Jonathan Swartz &lt;<a href="mailto:swartz@pobox.com">swartz@pobox.com</a>&gt;, Dave Rolsky &lt;<a href="mailto:autarch@urth.org">autarch@urth.org</a>&gt;, Ken Williams &lt;<a href="mailto:ken@mathforum.org">ken@mathforum.org</a>&gt;</p>
<p>
</p>
<hr />
<h1><A NAME="see_also">SEE ALSO</a></h1>
<p><a HREF="Mason.html">HTML::Mason</a>,
<a HREF="Admin.html">HTML::Mason::Admin</a>,
<a HREF="Request.html">HTML::Mason::Request</a></p>

</body>

</html>