Most common build-in functions or operators beginners should know about Perl

if (defined $x)

check a value or variable is undef or not.

undef $x;

reset a variable to undef.

qq, double-q operator; q, single-q operator

print qq(The "name" is "$name"\n);
print qq(The (name) is "$name"\n);
print qq{The )name( is "$name"\n};
print q[The )name} is "$name"\n];

The result will be:

The "name" is "foo"
The (name) is "foo"
The )name( is "foo"
The )name} is "$name"\n

x is repetition operator.

say "2" x 4;

will print the result:



use Scalar::Util qw(looks_like_number);
my $z = 3;
say $z;
my $y = "3.14";
if (looks_like_number($z) and looks_like_number($y)) {
    say $z + $y;

String comparison operators: eq, ne, lt, gt, le, ge

String functions: length, lc, uc, index, substr

my $str = "The black cat climbed the green tree";
say index $str, 'cat'; # 10
my $str = "The black cat climbed the green tree";
say substr $str, 4, 5; # black

int(): Integer part of a fractional number

rand(): Random numbers, A call to the rand($n) function of Perl will return a random fractional number between 0 and $n. It can be 0 but not $n.

last: skip the rest of the block and won’t check the condition again.

while (1) {
   print "Which programming language are you learning now? ";
    my $name = <STDIN>;
    chomp $name;
    if ($name eq 'Perl') {
    say 'Wrong! Try again!';
say 'done';

exit: exit the script running

Redirect standard output or standard error:

perl > output_log
perl 2 > error_log 
perl 2 > /dev/null #black hole

print scalar keys %hash;

size of the hash.

&func1 #function call

$_ #default input and pattern-searching space

$. current line number for the last filehandler accessed

$0 name of the programming being executed

$$ process number of the Perl running the script

$! yield the current value of error message

$@ the perl syntax error message from the last eval() operator


Note that you need to add

use Scalar::Util qw(looks_like_number);

to the program before being able to call looks_like_number()

I think it's much better to write:
say "2" x "4";
say "2" x 4;
to make it perfectly clear the right operand is an integer.

Leave a comment

About flymike

user-pic Keep it simple, stupid.