perl-begin / src / tutorials / bad-elements / index.html.wml

   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
#include '../template.wml'
#include "xhtml/1.x/std/toc.wml"

<latemp_subject "Perl Elements to Avoid" />

<latemp_more_keywords "elements, antipatterns, anti, patterns, help, ancient, ancient perl, modern, modern perl, avoid, bad perl, old tutorials, what to avoid" />

<h2 id="intro">Introduction</h2>

<p>
Often when people ask for help with Perl code, they show Perl code that
suffers from many bad or outdated elements. This is expected, as there
are many bad Perl tutorials out there, and lots of bad code that people
have learned from, but it is still not desirable. In order to not get
"yelled at" for using these, here is the document of the bad elements that
people tend to use and some better practices that should be used instead.
</p>

<p>
A book I read said, that as opposed to most previous idea systems, they
were trying to <b>liquidate negatives</b> instead of instilling positives
in people. So in the spirit of liquidating negatives, this tutorial-in-reverse
aims to show you what <b>not to do</b>.
</p>

<h2* id="toc">Table of Contents</h2*>

<toc />

<h2 id="bad-elements">The List of Bad Elements</h2>

<define-tag main_list endtag="required" whitespace="delete">
{#MAIN_LIST#:%body:##}
</define-tag>

<define-tag bad_code endtag="required">
<pre class="bad_code">
\# Bad code:

%body
</pre>
</define-tag>

{#MAIN_LIST#}

<define-tag item endtag="required">

<preserve id h />
<set-var %attributes />

<div class="element item">

<h3 id="<get-var id />"><get-var h /></h3>

%body

</div>

<restore id h />
</define-tag>

<main_list>

<item id="no-indentation" h="No Indentation">

<p>
<a href="http://en.wikipedia.org/wiki/Indent_style">Indentation</a> means
that the contents of every block are promoted from their containing environment
by using a shift of some space. This makes the code easier to read and follow.
</p>

<p>
Code without indentation is harder to read and so should be avoided.
<a href="http://en.wikipedia.org/wiki/Indent_style">The Wikipedia article</a>
lists several styles - pick one and follow it.
</p>

</item>

<item id="no-strict-and-warnings" h="No &quot;use strict;&quot; and &quot;use warnings;&quot;">

<p>
All modern Perl code should have the "use strict;" and "use warnings;" pragmas
that prevent or warn against misspelling variable names, using undefined
values, and other bad practices. So start your code (in every file) with this:
</p>

<pre>
#!/usr/bin/env perl

use strict;
use warnings;
</pre>

<p>
Or:
</p>

<pre>
package MyModule;

use strict;
use warnings;
</pre>

</item>

<item id="open-function-style" h="Correct style for using the open function">

<p>
<a href="http://perldoc.perl.org/functions/open.html">The open function</a>
is used to open files, sub-processes, etc. The correct style for it is:
</p>

<pre>
open my $input_fh, "&lt;", $input_filename
    or die "Could not open '$input_filename' - $!";
</pre>

<p>
the ultimately <b>wrong</b>, insecure and/or outdated styles are:
</p>

<pre>
\# Bareword filehandle (type glob), two arguments open (insecure) and no
\# error handling
open INPUT, "&lt;$filename";

\# Also opens from $INPUT.
open INPUT;
</pre>

</item>

<item id="calling-variables-file" h="Calling variables &quot;file&quot;">

<p>
Some people call their variables "file". However, file can mean either
<a href="http://en.wikipedia.org/wiki/File_descriptor">file handles</a>,
file names, or the contents of the file. As a result, this should be avoided
and one can use the abbreviations "fh" for file handle, or "fn" for filenames
instead.
</p>

</item>

<item id="identifiers-without-underscores" h="Identifiers without underscores">

<p>
Some people name their identifiers as several words all in lowercase and
not separated by underscores ("_"). As a result, this makes the code harder
to read. So instead of:
</p>

<pre>
my @listofnames;
</pre>

<p>
Say:
</p>

<pre>
my @list_of_names;
</pre>

<p>
Or maybe:
</p>

<pre>
my @names_list;
</pre>

</item>

<item id="prototypes" h="Don't use prototypes for subroutines">

<p>
Some people are tempted to declare their subroutines using
<tt>sub my_function ($$@)</tt>, with the signature of the accepted parameter
types, which is called a prototype. However, this tends to break code more
often than not, and should be avoided.
</p>

<p>
If you're looking for parameter lists to functions and methods, take a look
at <cpan_self_dist d="Devel-Declare" /> from
CPAN. But don't use prototypes.
</p>

<p>
For more information, see:
</p>

<ol>

<li>
<a href="https://www.socialtext.net/perl5/prototype">Discussion on the Perl 5 Wiki</a>
</li>

<li>
<a href="http://stackoverflow.com/questions/297034/why-are-perl-5s-function-prototypes-bad">“Why
are Perl 5’s function prototypes bad?”</a> on Stack Overflow.
</li>

</ol>


</item>

<item id="ampersand-in-subroutine-calls" h="Ampersand in Subroutine Calls">

<p>
One should not call a subroutine using <tt>&amp;myfunc(@args)</tt> unless
you're sure that is what you want to do (like overriding prototypes). Normally
saying <tt>myfunc(@args)</tt> is better.
</p>

</item>

<item id="assigning-from-dollar-underscore" h="Assigning from $_">

<p>
Some people write code like the following:
</p>

<pre>
while (&lt;$my_fh&gt;)
{
    my $line = $_;
    \# Do something with $line…
}
</pre>

<p>
Or:
</p>

<pre>
foreach (@users)
{
    my $user = $_;

    \# Process $user…
}
</pre>

<p>
However, you can easily assign the explicit and lexical variables in the
loop's opening line like so:
</p>

<pre>
while (my $line = &lt;$my_fh&gt;)
{
    \# Do something with $line…
}
</pre>

<p>
and:
</p>

<pre>
foreach my $user (@users)
{
    \# Process $user…
}
</pre>

</item>

<item id="foreach-lines" h="Using &quot;foreach&quot; on lines">

<p>
Some people may be tempted to write this code:
</p>

<pre>
foreach my $line (&lt;$my_file_handle&gt;)
{
    \# Do something with $line.
}
</pre>

<p>
This code appears to work but what it does is read the entire contents of the
file pointed by $my_file_handle into a (potentially long) list of lines, and
then iterate over them. This is inefficient. In order to read one line
at a time, use this instead:
</p>

<pre>
while (my $line = &lt;$my_file_handle&gt;)
{
    \# Do something with $line.
}
</pre>

</item>

<item id="string-notation" h="String Notation">

<p>
Perl has a flexible way to write strings and other delimiters, and you should
utilize it for clarity. If you find yourself writing long strings, write them
as <a href="http://en.wikipedia.org/wiki/Here_document">here-documents</a>:
</p>

<pre>
my $long_string_without_interpolation = &lt;&lt;'EOF';
Hello there. I am a long string.
I am part of the string.
And so am I.
EOF

# do stuff with $long_string_without_interpolation
</pre>

<p>
There are also <tt>&lt;&lt;"EOF"</tt> for strings with interpolation
and <tt>&lt;&lt;`EOF`</tt> for trapping command output. Make sure you never
use bareword here documents <tt>&lt;&lt;EOF</tt> which are valid syntax,
but many people are never sure whether they are <tt>&lt;&lt;"EOF"</tt> or
<tt>&lt;&lt;'EOF'</tt>.
</p>

<p>
If your strings are not too long but contain the special characters that
correspond with the default delimiters (e.g: <tt>'</tt>, <tt>"</tt>,
<tt>`</tt>, <tt>/</tt> etc.), then you can use the initial letter followed
by any arbitrary delimiter notation: <tt>m{\A/home/sophie/perl}</tt>,
<tt>q/My name is 'Jack' and I called my dog "Diego"./</tt>.
</p>

</item>

<item id="slurp" h="Slurping a file (i.e: Reading it all into memory)">

<p>
One can see several bad ways to read a file into memory in Perl. Among them
are:
</p>

<pre>
\# Not portable and suffers from possible
\# shell code injection.
my $contents = `cat $filename`;

\# Wasteful of CPU and memory:
my $contents = join("", &lt;$fh&gt;);

\# Even more so:
my $contents = '';
while (my $line = &lt;$fh&gt;)
{
    $contents .= $line;
}
</pre>

<p>
You should avoid them all. Instead the proper way to read an entire file
into a long string is to either use CPAN distributions for that such as
<cpan_self_dist d="File-Slurp" /> or
<cpan_self_dist d="IO-All" />, or alternatively
write down the following function and use it:
</p>

<pre>
sub _slurp
{
    my $filename = shift;

    open my $in, '&lt;', $filename
        or die "Cannot open '$filename' for slurping - $!";

    local $/;
    my $contents = &lt;$in&gt;;

    close($in);

    return $contents;
}
</pre>

</item>

<item id="paragraphs" h="Write code in Paragraphs using Empty Lines">

<p>
If one of your blocks is long, split it into "code paragraphs", with empty
lines between them and with each paragraph doing one thing. Then, it may be a
good idea to precede each paragraph with a comment explaining what it does, or
to extract it into its own function or method.
</p>

</item>

<item id="io-socket" h="Use IO::Socket and friends instead of lower-level calls">

<p>
One should use <cpan_mod m="IO::Socket">the IO::Socket</cpan_mod> family of
modules for networking Input/Output instead of the
lower-level socket()/connect()/bind()/etc. calls. As of this writing,
<pdoc d="perlipc"></pdoc> contains outdated information demonstrating how
to use the lower-level API which is not recommended.
</p>

</item>

<item id="subroutine-arguments" h="Subroutine Arguments Handling">

<p>
The first thing to know about handling arguments for subroutines is to avoid
refering to them directly by index. Imagine you have the following code:
</p>

<pre>
sub my_function
{
    my $first_name = $_[0];
    my $street = $_[1];
    my $city = $_[2];
    my $country = $_[3];
    .
    .
    .
}
</pre>

<p>
Now, what if you want to add <tt>$last_name</tt> between <tt>$first_name</tt>
and <tt>$street</tt>?
You'll have to promote all the indexes after it! Moreover, this scheme
is error-prone and you may reuse the same index more than once, or
miss some indexes.
</p>

<p>
Instead do either:
</p>

<pre>
sub my_function
{
    my $first_name = shift;
    my $street = shift;
    my $city = shift;
    my $country = shift;
    .
    .
    .
}
</pre>

<p>
Or:
</p>

<pre>
sub my_function
{
    my ($first_name, $street, $city, $country) = @_;
    .
    .
    .
}
</pre>

<p>
The same thing holds for unpacking <tt>@ARGV</tt>, the array containing the
command-line arguments for a Perl program, or any other array. Don't use
<tt>$ARGV[0]</tt>, <tt>$ARGV[1]</tt> etc. directly, but instead unpack
<tt>@ARGV</tt> using the methods given above. For processing
command line arguments, you should also consider using
<cpan_self_mod m="Getopt::Long" />.
</p>

<h4 id="clobbering-arrays-or-hashes">Don't clobber arrays or hashes</h4>

<p>
Often people ask how to pass arrays or hashes to subroutines. The answer is
that the right way to do it is to pass them as a reference as an argument
to the subroutine:
</p>

<pre>
sub calc_polynomial
{
    my ($x, $coefficients) = @_;

    my $x_power = 1;

    my $result = 0;

    foreach my $coeff (@{$coefficients})
    {
        $result += $coeff * $x_power;
    }
    continue
    {
        $x_power *= $x;
    }

    return $result;
}

print "(4*x^2 + 2x + 1)(x = 5) = ", calc_polynomial(5, [1, 2, 4]);
</pre>

<p>
You shouldn't clobber the subroutine's arguments list with entire arrays
or hashes (e.g: <tt>my_func(@array1, @array2);</tt> or
<tt>my_func(%myhash, $scalar)</tt> ), as this will make it difficult to
extract from <tt>@_</tt>.
</p>

<h4 id="named-parameters">Named Parameters</h4>

<p>
If the number of parameters that your subroutine accepts gets too long, or
if you have too many optional parameters, make sure you convert it to use
named arguments. The standard way to do it is to pass a hash reference or
a hash of arguments to the subroutine:
</p>

<pre>
sub send_email
{
    my $args = shift;

    my $from_address = $args-&gt;{from};
    my $to_addresses = $args-&gt;{to};
    my $subject = $args-&gt;{subject};
    my $body = $args-&gt;{body};
    .
    .
    .
}

send_email(
    {
        from =&gt; 'shlomif@perl-begin.org',
        to =&gt; ['shlomif@perl-begin.org', 'sophie@perl-begin.org'],
        subject =&gt; 'Perl-Begin.org Additions',
        .
        .
        .

    }
);
</pre>

</item>

<item id="chop" h="Avoid using chop() to trim newlines characters from lines">

<p>
Don't use <a href="http://perldoc.perl.org/functions/chop.html">the built-in
function chop()</a> in order to remove newline characters from the end
of lines read using the diamond operator (<tt>&lt;&gt;</tt>), because this
may cause the last character in a line without a line feed character to be
removed. Instead, use <a
href="http://perldoc.perl.org/functions/chomp.html">chomp()</a>.
</p>

<p>
If you expect to process DOS/Windows-like text files whose lines end with the
dual Carriage Return-Line Feed character on Unix systems then use the
following in order to trim them: <tt>$line =~ s/\x0d?\x0a\z//;</tt>.
</p>

<p>
For more information see:
</p>

<ul>
<li>
<a href="http://onlamp.com/pub/a/onlamp/2006/08/17/understanding-newlines.html">"Understanding Newlines"</a> - by Xavier Noria on OnLAMP.com.
</li>
<li>
<a href="http://en.wikipedia.org/wiki/Newline">Wikipedia article about newlines</a>
</li>
</ul>

</item>

<item id="lowercase_modules_and_pkgs" h="Don't start Modules and Packages with a Lowercase Letter">

<p>
Both modules and packages (the latter also known as namespaces) and all
intermediate components thereof should always start with an uppercase letter,
because modules and packages that start with a lowercase letter are
reserved for pragmas. So this is bad:
</p>

<bad_code>
\# This is file person.pm
package person;

use strict;
use warnings;
1;
</bad_code>

<p>
And this would be better:
</p>

<pre>
\# Better code!
\# This is file MyProject/Person.pm
package MyProject::Person;

use strict;
use warnings;
.
.
.
1;
</pre>

</item>

<item id="indirect-object-notation" h="Avoid Indirect Object Notation">

<p>
Don't use the so-called "Indirect-object notation" which can be seen in a lot
of old code and tutorials and is more prone to errors:
</p>

<bad_code>
my $new_object = new MyClass @params;
</bad_code>

<p>
Instead use the <tt>MyClass-&gt;new(…)</tt> notation:
</p>

<pre>
my $new_object = MyClass-&gt;new(@params);
</pre>

</item>

<item id="dollar-dollar" h="$$myarray_ref[$idx] or $$myhash_ref{$key}">

<p>
Don't write <tt>$$myarray_ref[$idx]</tt>, which is cluttered and can be easily
confused with <tt>(${$myarray_ref})-&gt;[$idx]</tt>. Instead, use the
arrow operator - <tt>$myarray_ref-&gt;[$idx]</tt>. This also applies for
hash references - <tt>$myhash_ref-&gt;{$key}</tt>.
</p>

</item>

<item id="c-style-for-loops" h="C-style for loops">

<p>
Some beginners to Perl tend to use C-style-for-loops to loop over an array's
elements:
</p>

<pre>
for (my $i=0 ; $i &lt; @array ; $i++)
{
    \# Do something with $array[$i]
}
</pre>

<p>
However, iterating over the array itself would normally be preferable:
</p>

<pre>
foreach my $elem (@array)
{
    \# Do something with $elem.
}
</pre>

<p>
If you still need the index, do:
</p>

<pre>
foreach my $idx (0 .. $#array)
{
    my $elem = $array[$idx];

    \# Do something with $idx and $elem.
}

\# perl-5.12.0 and above:
foreach my $idx (keys(@array))
{
    my $elem = $array[$idx];

    \# Do something with $idx and $elem.
}

\# Also perl-5.12.0 and above.
while (my ($idx, $elem) = each(@array))
{
    \# Do something with $idx and $elem.
}
</pre>

<p>
An arbitrary C-style for loop can be replaced with a while loop with
a <tt>continue</tt> block.
</p>

</item>

<item id="non-intrusive-commenting" h="Avoid Intrusive Commenting">

<p>
Some commenting is too intrusive and interrupts the flow of reading the code.
Examples for that are the <tt>########################</tt> hard-rules that
some people put in their code, the comments using multiple
<a href="http://en.wikipedia.org/wiki/Number_sign">number signs ("#")</a>,
like <tt>####</tt>, or excessively long comment block. Please avoid all those.
</p>

<p>
Some schools of software engineering argue that if the code's author feels
that a comment is needed, it usually indicates that the code is not clear
and should be factored better (like extracting a method or a subroutine with
a meaningful name.). It probably does not mean that you should avoid writing
comments altogether, but excessive commenting could prove as a red flag.
</p>

<p>
If you're interested in documenting the public interface of your modules and
command-line programs, refer to <pdoc d="perlpod">, Perl's Plain Old
Documentation (POD)</pdoc>, which allows one to quickly and easily document
one's code. POD has
<a href="http://search.cpan.org/search?query=pod&amp;mode=all">many extensions
available on CPAN</a>, which may prove of use.
</p>

</item>

<item id="accessing_object_slots_directly" h="Accessing Object Slots Directly">

<p>
Since <a href="$(ROOT)/topics/object-oriented/">Perl objects</a> are simple
references some programmers are tempted to access them directly:
</p>

<bad_code>
$self-&gt;{'name'} = "John";
print "I am ", $self-&gt;{'age'}, " years old\n";

\# Or even: (Really bad code)
$self-&gt;[NAME()] = "John";
</bad_code>

<p>
However, this is sub-optimal as explained in
<a href="http://www.shlomifish.org/lecture/Perl/Newbies/lecture5/accessors/">the
Perl
for Newbies section about "Accessors"</a>, and one should use accessors
using code like that:
</p>

<pre>
\# Good code.
$self-&gt;_name("John");
print "I am ", $self-&gt;_age(), " years old\n";
</pre>

<p>
As noted in the link, you can use one of CPAN's many accessor generators to
generate accessors for you.
</p>

</item>

<item id="caret_and_dollar_sign_in_regexes" h="'^' and '$' in Regular Expressions">

<p>
Some people use "^" and "$" in regular expressions to mean
beginning-of-the-string or end-of-the-string. However, they can mean
beginning-of-a-line and end-of-a-line respectively using the <tt>/m</tt> flag
which is confusing. It's a good idea to use <tt>\A</tt> for start-of-string
and <tt>\z</tt> for end-of-string always, and to specify the <tt>/m</tt> flag
if one needs to use "^" and "$" for start/end of a line.
</p>

</item>

<item id="magic_numbers" h="Magic Numbers">

<p>
Your code should not include <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants">unnamed
numerical constants also known as "magic numbers" or "magic constants"</a>.
For example, there is one in this code to shuffle a deck of cards:
</p>

<bad_code>
for my $i (0 .. 51)
{
    my $j = $i + int(rand(52-$i));
    @cards[$i,$j] = @cards[$j,$i];
}
</bad_code>

<p>
This code is bad because the meaning of 52 and 51 is not explained and they
are arbitrary. A better code would be:
</p>


<pre>
\# Good code.
\# One of:
my $deck_size = 52;
Readonly my $deck_size =&gt; 52;

for my $i (0 .. $deck_size-1)
{
    my $j = $i + int(rand($deck_size-$i));
    @cards[$i,$j] = @cards[$j,$i];
}
</pre>

<p>
(Of course in this case, you may opt to use a shuffle function from CPAN,
but this is just for the sake of demonstration.).
</p>

</item>

<item id="vars_in_quotes" h="String Variables Enclosed in Double Quotes">

<p>
One can sometimes see people write code like that:
</p>

<bad_code>
my $name = shift(@ARGV);

print "$name", "\n";

if ("$name" =~ m{\At}i)
{
    print "Your name begins with the letter 't'";
}
</bad_code>

<p>
However, it's not necessary to enclose $name in double quotes (i.e:
<tt>"$name"</tt>) because it's already a string. Using it by itself as
<tt>$name</tt> will do just fine:
</p>

<pre>
\# Better code.
my $name = shift(@ARGV);

print $name, "\n";

if ($name =~ m{\At}i)
{
    print "Your name begins with the letter 't'";
}
</pre>

<p>
Also see <a href="$(ROOT)/uses/text-generation/">our page about text
generation</a> for other ways to delimit text.
</p>

<p>
Note that sometimes enclosing scalar variables in double-quotes makes sense -
for example if they are objects with overloaded stringification. But this is
the exception rather than the rule.
</p>

</item>

<item id="at-array-for-subscripting" h="@array[$idx] for array subscripting">

<p>
Some newcomers to Perl 5 would be tempted to write <tt>@array[$index]</tt>
to subscript a single element out of the array <tt>@array</tt>. However,
<tt>@array[$index]</tt> is a single-element array <b>slice</b>. To get
a single subscript out of <tt>@array</tt> use <tt>$array[$idx]</tt> (with
a dollar sign). Note that if you want to extract several elements, you can
use an array slice such as <tt>@array[@indexes]</tt> or
<tt>@array[$x,$y] = @array[$y,$x]</tt>. However, then it's a list which should
be used in list context.
</p>

</item>

<item id="vars-a-and-b" h="Variables called $a and $b">

<p>
One should not create lexical variables called <tt>$a</tt> and <tt>$b</tt>
because there are built-in-variables called that used for
<pdoc_f f="sort">sorting</pdoc_f> and other uses (such as reduce in
<cpan_self_mod m="List::Util" />), which the lexical variables will interfere
with:
</p>

<bad_code>
my ($a, $b) = @ARGV;
.
.
.
\# Won't work now.
my @array = sort { length($a) &lt;=&gt; length($b) } @other_array;
</bad_code>

<p>
Instead, use other single-letter variable names such as
<tt>$x</tt> and <tt>$y</tt>, or better yet give more descriptive names.
</p>

</item>

<item id="flow-stmts-without-labels" h="Flow Control Statements Without an Explicit Label">

<p>
One can sometimes see flow-control statements such as
<pdoc_f f="next"><b>next</b></pdoc_f>, <pdoc_f f="last"><b>last</b></pdoc_f> or
<pdoc_f f="redo"><b>redo</b></pdoc_f> used without an explicit label following
them, in which case they default to re-iterating or breaking out of the
innermost loop. However, this is inadvisable, because later on, one may modify
the code to insert a loop in between the innermost loop and the flow control
statement, which will break the code. So always append a label to "next",
"last" and "redo" and label your loops accordingly:
</p>

<pre>
LINES:
while (my $line = &lt;&gt;)
{
    if ($line =~ m{\A#})
    {
        next LINES;
    }
}
</pre>

</item>

<item id="abuse_of_array_last_index" h="($#array + 1) and Other Abuses of $#.">

<p>
The <tt>$#array</tt> notation gives the last index in <tt>@array</tt> and
is always equal to the array length minus one. Some people use it to signify
the length of the array:
</p>

<bad_code>
my @flags = ((0) x ($#names +1))
</bad_code>

<p>
However this is unnecessary because one can better do it by evaluating
<tt>@names</tt> in scalar context, possibly by saying <tt>scalar(@names)</tt>.
</p>

<pre>
\# Better code.
my @flags = ((0) x @names);
</pre>

</item>

<item id="last_elems_of_array" h="$array[$#array], $array[$#array-1], etc.">

<p>
One can sometimes see people references the last elements of arrays using
notation such as <tt>$array[$#array]</tt>, <tt>$array[$#array-1]</tt>
or even <tt>$array[scalar(@array)-1]</tt>. This duplicates the identifier
and is error prone and there's a better way to do it in Perl using
negative indexes. <tt>$array[-1]</tt> is the last element of the array,
<tt>$array[-2]</tt> is the second-to-last, etc.
</p>

</item>

<item id="re_string_interpolate" h="Interpolating Strings into Regular Expressions">

<p>
One can often see people interpolate strings directly into regular expressions:
</p>

<bad_code>
my $username = shift(@ARGV);

open my $pass_fh, '&lt;', '/etc/passswd'
    or die "Cannot open /etc/passwd - $!";

PASSWD:
while (my $line = &lt;$pass_fh&gt;)
{
    if ($line =~ m{\A$username}) \# Bad code here.
    {
        print "Your username is in /etc/passwd\n";
        last PASSWD;
    }
}
close($pass_fh);
</bad_code>

<p>
The problem is that when a string is interpolated into a regular expression
it is interpolated as a mini-regex, and special characters there behave like
they do in a regular expression. So if I input <tt>'.*'</tt> into the command
line in the program above, it will match all lines. This is a special case
of <a href="http://community.livejournal.com/shlomif_tech/35301.html">code
or markup injection</a>.
</p>

<p>
The solution to this is to use \Q and \E to signify a
<pdoc_f f="quotemeta">quotemeta()</pdoc_f> portion that will treat the
interpolated strings as plaintext with all the special characters escaped.
So the line becomes: <tt>if ($line =~ m{\A\Q$username\E})</tt>.
</p>

<p>
Alternatively, if you do intend to interpolate a sub-regex, signify this
fact with a comment. And be careful with regular expressions that are accepted
from user input.
</p>

</item>

<item id="overuse_dollar_underscore" h="Overusing $_">

<p>
It's a good idea not to overuse <tt>$_</tt> because using it, especially in
large scopes, is prone to errors, including many subtle ones. Most Perl
operations support operating on other variables and you should use lexical
variables with meaningful names instead of $_ whenever possible.
</p>

<p>
Some places where you have to use <tt>$_</tt> are <pdoc_f f="map">map</pdoc_f>,
<pdoc_f f="grep">grep</pdoc_f> and other functions like that, but even in
that case it might be desirable to set a lexical variable to the value of
<tt>$_</tt> right away: <tt>map { my $line = $_; … } @lines</tt>.
</p>

</item>

<item id="mixing_tabs_and_spaces" h="Mixing Tabs and Spaces">

<p>
Some improperly configured text editors may be used to write code that, while
indented well at a certain tab size looks terrible on other tab sizes, due
to a mixture of tabs and spaces. So either use tabs for indentation or make
sure your tab key expands to a constant number of spaces. You may also wish
to make use of <cpan_self_dist d="Perl-Tidy" /> to properly format your
code.
</p>

</item>

<item id="qx_for_command_execution" h="`…` or qx// for Executing Commands">

<p>
Some people are tempted to use backticks (<tt>`…`</tt>) or <tt>qx/…/</tt>
for executing commands for their side-effects. E.g:
</p>

<bad_code>
use strict;
use warnings;

my $temp_file = "tempfile.txt";

`rm -f $temp_file`;
</bad_code>

<p>
However, this is not idiomatic because <tt>`…`</tt> and <tt>qx/…/</tt> are
used to trap a command's output and to return it as a big string or as a list
of lines. It would be a better idea to use
<pdoc_f f="system">system()</pdoc_f> or to seek more idiomatic Perl-based
solutions on CPAN or in the Perl core (such as using
<pdoc_f f="unlink">unlink()</pdoc_f> to delete a file in our case.).
</p>

<p>
Some people even go and ask how to make the <tt>qx/…/</tt> output go to
the screen, which is a clear indication that they want to use system().
</p>

</item>

<item id="explicit_return" h="No Explicit Returns">

<p>
As noted in "Perl Best Practices", all functions must have an explicit
<tt>return</tt> statement, as otherwise they implicitly return the last
expression, which would be subject to change upon changing the code. If you
don't want the subroutine to return anything (i.e: it's a so-called
"procedure"), then write <tt>return;</tt> to always return a false value,
which the caller won't be able to do anything meaningful with.
</p>

<p>
Another mistake is to write "return 0;" or "return undef;" to return
false, because in list context, they will return a one-element list which
is considered true. So always type <tt>return;</tt> to return false.
</p>

</item>

<item id="varvarname" h="&quot;Varvarname&quot; - Using a variable as another variable's name.">

<p>
Mark Jason Dominus has written about
<a href="http://perl.plover.com/varvarname.html">varvarname -
"Why it's stupid to `use a variable as a variable name'"</a>, namely if
<tt>$myvar</tt> is <tt>'foobar'</tt> they want to operate on the value of
<tt>$foobar</tt>. While there are ways to achieve similar things in Perl,
the best way is to use <a href="$(ROOT)/topics/hashes/">hashes</a> (possibly
pointing to complex records with more information) and lookup them by
the string you want to use. Read the link by MJD for more information.
</p>

</item>

<item id="leading_underscores" h="Use Leading Underscores ('_') for Internal Methods and Functions">

<p>
When writing a module use leading underscores in identifiers of methods and
functions to signify those that are: 1. Subject to change. 2. Are used
internally by the module. 3. Should not be used from outside. By using
<cpan_self_dist d="Pod-Coverage" /> one can make sure that the external API
of the module is documented and it will skip the identifiers with leading
underscores, that can be thought of as "private" ones.
</p>

<p>
Here's an example:
</p>

<pre>
package Math::SumOfSquares;

use strict;
use warnings;

use List::Utils qw(sum);

sub _square
{
    my $n = shift;

    return $n * $n;
}

sub sum_of_squares
{
    my ($numbers) = @_;

    return sum(map { _square($_) } @$numbers);
}

1;
</pre>
</item>

<item id="print_to_fh" h="print $fh @args">

<p>
It is preferable to write <tt>print {$write_fh} @args</tt>
over <tt>print $write_fh @args</tt> because the latter can more easily be
mistaken for <tt>print $write_fh, @args</tt> (which does something different)
and does not provide enough visual hints that you are writing to the
<tt>$write_fh</tt> filehandle. Therefore, always wrap the file-handle in
curly braces (so-called "dative block"). (Inspired by "Perl Best Practices").
</p>

</item>

<item id="STDIN_instead_of_ARGV" h="Using STDIN instead of ARGV">

<p>
One can write code while reading from STDIN:
</p>

<bad_code>
use strict;
use warnings;

\# Strip comments.

LINES:
while (my $line = &lt;STDIN&gt;)
{
    if ($line =~ m{\A *#})
    {
        next LINES;
    }
    print $line;
}
</bad_code>

<p>
However, it is usually better to use <tt>ARGV</tt> instead of <tt>STDIN</tt>
because it also allows processing the filenames from the command line. This
can also be achieved by simply saying <tt>&lt;&gt;</tt>. So the code becomes:
</p>

<pre>
\# Better code:

use strict;
use warnings;

\# Strip comments.

LINES:
while (my $line = &lt;&gt;)
{
    if ($line =~ m{\A *#})
    {
        next LINES;
    }
    print $line;
}
</pre>

</item>

<item id="modifying_iterated_array" h="Modifying arrays or hashes while iterating through them.">

<p>
Some people ask about how to add or remove elements to an existing array or
hash when iterating over them using <tt>foreach</tt> and other loops. The
answer to that is that Perl will likely not handle it too well, and it expects
that during loops the keys of a data structure will remain constant.
</p>

<p>
The best way to achieve something similar is to populate a new array or hash
during the loop by using <pdoc_f f="push">push()</pdoc_f> or a hash lookup
and assignment. So do that instead.
</p>
</item>

<item id="code_in_foreign_lang" h="Comments and Identifiers in a Foreign Language">

<p>
Apparently, many non-native English speakers write code with comments and
even identifiers in their native language. The problem with this is that
programmers who do not speak that language will have a hard time understanding
what is going on here, especially after the writers of the foreign language
code post it in to an Internet forum in order to get help with it.
</p>

<p>
Consider what Eric Raymond wrote in
<a href="http://www.catb.org/~esr/faqs/hacker-howto.html#skills4">his
"How to Become a Hacker" document</a> (where hacker is a software enthusiast
and not a computer intruder):
</p>

<blockquote>
<p>
4. If you don't have functional English, learn it.
</p>

<p>
As an American and native English-speaker myself, I have previously been
reluctant to suggest this, lest it be taken as a sort of cultural imperialism.
But several native speakers of other languages have urged me to point out that
English is the working language of the hacker culture and the Internet, and
that you will need to know it to function in the hacker community.
</p>

<p>
Back around 1991 I learned that many hackers who have English as a second
language use it in technical discussions even when they share a birth tongue;
it was reported to me at the time that English has a richer technical
vocabulary than any other language and is therefore simply a better tool for
the job. For similar reasons, translations of technical books written in
English are often unsatisfactory (when they get done at all).
</p>

<p>
Linus Torvalds, a Finn, comments his code in English (it apparently never
occurred to him to do otherwise). His fluency in English has been an important
factor in his ability to recruit a worldwide community of developers for Linux.
It's an example worth following.
</p>

<p>
Being a native English-speaker does not guarantee that you have language skills
good enough to function as a hacker. If your writing is semi-literate,
ungrammatical, and riddled with misspellings, many hackers (including myself)
will tend to ignore you. While sloppy writing does not invariably mean sloppy
thinking, we've generally found the correlation to be strong — and we have no
use for sloppy thinkers. If you can't yet write competently, learn to.
</p>
</blockquote>

<p>
So if you're posting code for public scrutiny, make sure it is written with
English identifiers and comments.
</p>

</item>

<item id="perlform" h="Using perlform for formatting text.">

<p>
One should not use <tt>perlform</tt> for formatting text, because it makes
use of global identifiers, and should use the
<cpan_self_dist d="Perl6-Form" /> CPAN distribution instead. Also see
our <a href="$(ROOT)/uses/text-generation/">text generation page</a> for
more information. (Inspired by "Perl Best Practices").
</p>

</item>

<item id="obj_new" h="Using $obj->new for object construction.">

<p>
Sometimes you can see class constructors such as:
</p>

<bad_code>
sub new
{
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self  = {};
}
</bad_code>

<p>
The problem here is that this allows one to do
<tt>$my_object_instance-&gt;new</tt> to create a new instance of the object,
but many people will expect it to be invalid or to clone the object. So don't
do that and instead write your constructors as:
</p>

<pre>
\# Better code:

sub new
{
    my $class = shift;
    my $self  = {};

    bless $self, $class;
}
</pre>

<p>
Which will disable it and will just allow
<tt>ref($my_object_instance)-&gt;new(…)</tt>. If you need a clone method,
then code one called "clone()" and don't use "new" for that.
</p>

<p>
(Thanks to
<a href="http://www.stonehenge.com/merlyn/UnixReview/col52.html">Randal L.
Schwartz's post "Constructing Objects"</a> for providing the insight to this).
</p>

</item>

<item id="law_of_demeter" h="Law of Demeter">

<p>
See the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Wikipedia article
about "Law of Demeter" for more information</a>. Namely, doing many nested
method calls like
<tt>$self-&gt;get_employee('sophie')-&gt;get_address()-&gt;get_street()</tt>
is not advisable, and should be avoided.
</p>

<p>
A better option would be to provide methods in the containing objects to
access those methods of their contained objects. And an even better way would
be to structure the code so that each object handles its own domain.
</p>

</item>

<item id="delegating_parameter_passing" h="Passing parameters in delegation">

<p>
Sometimes we encounter a case where subroutines each pass the same parameter
to one another in delegation, just because the innermost subroutines in the
callstack need it.
</p>

<p>
To avoid it, create a class, and declare methods that operate on the
fields of the class, where you can assign the delegated arguments.
</p>

</item>

<item id="duplicate_code" h="Duplicate Code">

<p>
As noted in
<a href="http://www.shlomifish.org/philosophy/books-recommends/#refactoring">Martin
Fowler's "Refactoring"</a> book (but held as a fact for a long time
beforehand),
<a href="http://en.wikipedia.org/wiki/Duplicate_code">duplicate code</a> is a
code smell, and should be avoided. The solution is to extract duplicate
functionality into subroutines, methods and classes.
</p>

</item>

<item id="long_functions" h="Long Functions and Methods">

<p>
Another common code smell is
<a href="http://c2.com/cgi/wiki?LongMethodSmell">long
subroutines and methods</a>. The solution to these is to extract several
shorter methods out, with meaningful names.
</p>

</item>

<item id="map_instead_of_foreach" h="Using map instead of foreach for side-effects">

<p>
You shouldn't be using <pdoc_f f="map">map</pdoc_f> to iterate on a list
instead of foreach if you're not interested in constructing a new list and
all you are interested in are the side-effects. For example:
</p>

<bad_code>

use strict;
use warnings;

map { print "Hello $_!\n"; } @ARGV;
</bad_code>

<p>
Would be better written as:
</p>

<pre>


use strict;
use warnings;

foreach my $name (@ARGV)
{
    print "Hello $name!\n";
}
</pre>

<p>
Which better conveys one's intention and may be a bit more efficient.
</p>

</item>

<item id="ternary_operator_instead_of_if_else" h="Using the ternary operator for side-effects instead of if/else">

<p>
A similar symptom to the above is people who wish to use the ternary
inline- conditional operator (<tt>? :</tt>) for choosing to execute between
two different statements with side-effects
instead of using <tt>if</tt> and <tt>else</tt>. For example:
</p>

<bad_code>
$cond_var ? ($hash{'if_true'} .= "Cond var is true")
          : ($hash{'if_false'} .= "Cond var is false")
</bad_code>

<p>
(This is assuming the ternary operator was indeed written correctly, which
is not always the case).
</p>

<p>
However, the ternary operator is meant to be an expression that is a choice
between two values and should not be used for its side-effects. To do the
latter, just use <tt>if</tt> and <tt>else</tt>:
</p>

<pre>
if ($cond_var)
{
    $hash{'if_true'} .= "Cond var is true";
}
else
{
    $hash{'if_false'} .= "Cond var is false";
}
</pre>

<p>
This is safer, and better conveys one’s intentions.
</p>

<p>
For more information, refer to
<a href="http://www.nntp.perl.org/group/perl.beginners/2012/04/msg120480.html">a
relevant thread on the Perl beginners mailing list</a> (just make sure you read
it in its entirety).
</p>

</item>

<item id="nested_top_level_subroutines" h="Nested top-level subroutines">

<p>
One should not nest an inner top-level subroutine declared using
<tt>sub inner</tt> inside of an outer one, like so:
</p>

<bad_code>
sub outer
{
    sub inner
    {
        .
        .
        .
    }

    \# Use inner here
}
</bad_code>

<p>
This code will compile and run, but may break in subtle ways.
</p>

<p>
The first problem with this approach is that <tt>inner()</tt> will still be
visible outside <tt>outer()</tt>, but the more serious problem is that the
inner subroutine will only get one copy of the lexical variables inside
<tt>outer()</tt>.
</p>

<p>
The proper and safer way to declare an inner subroutine is to declare
a lexical variable and set it to an anonymous subroutine, which is
also known as a closure:
</p>

<pre>
sub outer
{
    my ($foo, $bar) = @_;

    my $print_foo = sub {
        print "Foo is '$foo'\n";

        return;
    };

    $print_foo-&gt;();

    $foo++;

    $print_foo-&gt;();

    return;
}
</pre>

</item>

<item id="grep_instead_of_any" h="Using grep instead of any and friends">

<p>
Sometimes one can see people using <pdoc_f f="grep">grep</pdoc_f> to find
the first matching element in an array, or whether such an element exists at
all. However, grep is intended to extract <b>all</b> matching elements out
of a list, not just the first one, and as a result will not stop until it
finds them all. To remedy this look at either <tt>first()</tt> from
<cpan_self_mod m="List::Util" /> (to find the first match) or
"any/all/notall/none" from <cpan_self_mod m="List::MoreUtils" /> (to find
whether a single element exists). These better convey one's intention
and may be more efficient because they stop on the first match.
</p>

<p>
One should note that if one does such lookups often, then they should try
to use a <a href="$(ROOT)/topics/hashes/">hash</a> instead.
</p>

</item>

<item id="FileHandle_module" h="Using the FileHandle Module">

<p>
The FileHandle module is old and bad, and should not be used. One should
use the <a href="http://perldoc.perl.org/IO/Handle.html">IO::Handle</a>
family of modules instead.
</p>

</item>

<item id="file_includes" h="&quot;Including&quot; files instead of using Modules">

<p>
We are often asked how one can "include" a file in a Perl program (similar
to <a href="http://php.net/manual/en/function.include.php">PHP's include</a>
or <a href="http://ss64.com/bash/period.html">the shell's
"source" or "." operators</a>. The answer is that the better way is to extract
the common functionality from all the programs into
<a href="$(ROOT)/topics/modules-and-packages/">modules</a> and load them by
using "use" or "require".
</p>

<p>
Note that <pdoc_f f="do">do</pdoc_f> can be used to evaluate a file (but in
a different scope), but it's almost always not needed.
</p>

<p>
Some people are looking to supply a common configuration to their programs
as global variables in the included files, and those people should look at
CPAN configration modules such as <cpan_self_dist d="Config-IniFiles" />
or <a href="http://search.cpan.org/search?query=json&amp;mode=all">the
various JSON modules</a> for the ability to read configuration files
in a safer and better way.
</p>

</item>

<item id="global_vars_iface" h="Using Global Variables as an Interface to the Module">

<p>
While it is possible to a large extent, one should generally not use global
variables as an interface to a module, and should prefer having a procedural
or an object oriented interface instead. For information about this see our
<a href="$(ROOT)/topics/modules-and-packages/">page about modules and
packages</a> and our <a href="$(ROOT)/topics/object-oriented/">our page
about object oriented programming in Perl</a>.
</p>

</item>

<item id="declaring_all_vars_at_top" h="Declaring all variables at the top">

<p>
Some inexperienced Perl programmers, possibly by influence from languages
such as C, like to declare all variables used by the program at the top of
the program or the relevant subroutines. Like so:
</p>

<bad_code>
my $first_name;
my $last_name;
my $address;
my @people;
my %cities;
.
.
.
</bad_code>

<p>
However, this is bad form in Perl, and the preferable way is to declare all
the variables when they are first used, and at the innermost scope where they
should retain their value. This will allow to keep track of them better.
</p>

</item>

<item id="switch_pm" h="Using Switch.pm">

<p>
One should not use Switch.pm to implement a
<a href="http://en.wikipedia.org/wiki/Switch_statement">switch statement</a>
because it's a source filter, tends to break a lot of code, and causes
unexpected problems. Instead one should either use <tt>given/when</tt>, which
are only available in perl-5.10 and above, or dispatch tables, or alterantively
plain <tt>if/elsif/else</tt> structures.
</p>

</item>

<item id="threads" h="Using threads in Perl">

<p>
Some beginners, when thinking they need to multitask their programs start
thinking they should use perl threads. However, as mentioned in
<pdoc d="perlthrtut">perlthrtut</pdoc>, perl threads are very much unlike
the traditional thread modules, share nothing by default and are in fact
heavyweight processes (instead of the usual lightweight ones). See also
<a href="http://www.perlmonks.org/index.pl?node_id=288022">Elizabeth
Mattijsen’s writeup about perl's ithreads on perlmonks</a>.
</p>

<p>
To sum up, usually threads are the wrong answer and you should be using
forking processes or something like POE (see our
<a href="$(ROOT)/uses/multitasking/">page about multitasking</a>) instead.
</p>

</item>

<item id="calling-the-shell-too-much" h="Calling Shell Commands Too Much">

<p>
Some people are tempted to use shell commands for performing
various tasks using <tt>`…`</tt>, <tt>qx/…/</tt>, <tt>system()</tt>,
piped-open, etc. However, usually Perl has built-in routines or alternatively
CPAN modules, which are more portable, and often would be faster than
calling the shell for help, and they should be used instead.
</p>

<p>
As an extreme example, the site <i>The Daily WTF</i>
had <a href="http://thedailywtf.com/Articles/The_UNIX_Philosophy.aspx">a
feature</a> which featured the following code to determine the file size
in Perl:
</p>

<bad_code>
my $filesize = `wc -c $file | cut -c0-8 | sed 's/ //g'`;
</bad_code>

<p>
Reportedly, replacing this line with <tt>my $filesize = -s $file</tt> (which
as noted earlier should have been called <tt>$filename</tt> instead), resulted
in the program being 75 minutes faster on average (!).
</p>

<p>
Normally, if you find yourself using UNIX text processing commands such as
<tt>sed</tt>, <tt>awk</tt>, <tt>grep</tt>, and <tt>cut</tt>, you should
implement it in pure-Perl code.
</p>

</item>

<item id="missing-semicolons-at-the-end-of-blocks" h="Missing Semicolons at the end of blocks">

<p>
The perl interpreter allows one to omit the last trailing semicolon (";") in
the containing block. Like so:
</p>

<bad_code>
if ( COND() )
{
     print "Success!\n";
     call_routine() \# No semicolon here.
}
</bad_code>

<p>
However, this isn't a good idea, because it is inconsistent, and may cause
errors (or obscure failures) if one-or-more statements are added afterwards.
</p>

<p>
As a result, you should end every statement with a semicolon (";") even i
it’s the last one. A possible exception to this may be single-line and/or
single-statement blocks like in <pdoc_f f="map">map</pdoc_f>.
</p>

</item>

<item id="list-form-of-open-with-one-arg" h="List form of open with one argument.">

<p>
Recent versions of of perl introduced the list-forms of piping to and from a
command, such as <tt>open my $fh, '-|', 'fortune', $collection</tt> or
<tt>open my $printer, '|-', 'lpr', '-Plp1'</tt>. However, not only they are
not implemented on Windows and other UNIX-like systems yet, but when one passes
only one argument to them, they pass it to the shell verbatim.
</p>

<p>
As a result, if one passes an array variable to them, as in:
</p>

<bad_code>
open my $fh, '-|', @foo
    or die "Could not open program! - $!"
</bad_code>

<p>
One can pass only a single argument to <tt>@foo</tt>, which would be dangerous.
To mitigate that, one should use the <cpan_self_dist d="IPC-Run" />
or the <cpan_self_dist d="IPC-System-Simple" /> CPAN distributions.
</p>

</item>

</main_list>

#include "bad-elements-sources.wml"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.