Use non-word characters as variable names
Using $%
instead of $a
can allow you to place the variable name right next to an if
, for
or while
construct as in:
@r=(1,2,3,4,5);$%=4;
print$_*$%for@r
Many can be used, but check the docs and @BreadBox's answer for which ones have magic effects!
Use map when you can't use statement modifiers
If you can't use statement modfiers as per @JB's answer, map might save a byte:
for(@c){}
vs. map{}@c;
and is useful if you want to do nested iterations as you can put postfix for
loops inside the map
.
Use all the magic Regular Expression variables
Perl has magic variables for 'text before match' and 'text after match' so it is possible to split to groups of two with potentially fewer characters:
($x,$y)=split/,/,$_;
($x,$y)=/(.+),(.+)/;
/,/; # $x=$`, $y=$'
# Note: you will need to save the variables if you'll be using more regex matches!
This might also work well as a replacement for substr
:
$s=substr$_,1;
/./;# $s=$'
$s=substr$_,4;
/.{4}/;# $s=$'
If you need the contents of the match, $&
can be used, eg:
# assume input like '10 PRINT "Hello, World!"'
($n,$c,$x)=split/ /,$_;
/ .+ /; # $n=$`, $c=$&, $x=$'
Replace subs with long names with a shorter name
If you call say print
four or more times in your code (this obviously varies with the length of the routine you're calling), replace it with a shorter sub name:
sub p{print@_}p;p;p;p
vs.
print;print;print;print
Replace conditional incrementors/decrementors
If you have code like:
$i--if$i>0
you can use:
$i-=$i>0
instead to save some bytes.
Convert to integer
If you aren't assigning to a variable and so can't use breadbox's tip, you can use the expression 0|
:
rand 25 # random float eg. 19.3560355885212
int rand 25 # random int
0|rand 25 # random int
rand 25|0 # random int
~~rand 25 # random int
It's worth noting however than you don't need to use an integer to access an array index:
@letters = A..Z;
$letters[rand 26]; # random letter
$_=print""
is shorter than$_=print$foo
. – ASCIIThenANSI – 2015-12-18T18:23:13.9605The idea is that you already need to print
$foo
. Otherwise,$_=1
is much shorter than$_=print""
and has the same effect. – breadbox – 2016-02-19T23:59:13.2133For the third do you mean iterating over the chars in
$x
? Otherwise you could just do/./gs
and/./g
. – redbmk – 2016-04-14T10:44:10.163