1. Perl
  2. Frequently used functions/modules

List of frequently used functions/standard modules

This is a list of frequently used functions and standard modules. Remembering these functions can make Perl more useful. I avoid detailed explanations and introduce simple examples. Those with a return value are represented by the symbol $ret. Twice

It also explains frequently used predefined variable and standard modules. Each item also links to the details of the function, so please use it conveniently.

  1. math functions
  2. String manipulation
  3. Array operation
  4. hash operation
  5. File I/O
  6. File directory operations
  7. Time/Time
  8. Other important functions
  9. How to search function and module documentation
  10. Frequently used predefined variable
  11. Frequently used standard modules

Mathematical functions

abs

Use abs function to find the absolute value.

$ret = abs $num;

abs(-3) will be 3.

sqrt

To find the positive square root, use sqrt function.

$ret = sqrt $num;

sqrt(4) will be 2.

int

Use int function to retrieve the integer part of a number that includes a decimal point.

$ret = int $num;

int(1.5) becomes 1 and int(-1.5) becomes -1.

ceil(POSIX)

To round up the decimal point, use the POSIX module's ceil function.

use POSIX 'ceil';
$ret = ceil $num;

floor(POSIX)

To round down the decimal point, use floor function of the POSIX module.

use POSIX 'floor';
$ret = floor $num;

rand

Use rand function to generate random numbers. A number less than the number specified by the argument is randomly generated.

$ret = rand $num;

looks_like_number(Scalar::Util)

Use looks_like_number function of the Scalar::Util module to determine if it is a number.

use Scalar::Util 'looks_like_number';
$ret = looks_like_number $num;

2 String manipulation

join

Use join function to concatenate strings by specifying a delimiter.

$ret = join(',', @array);

The first argument is the delimiter. In this example, a comma is specified as the delimiter. The strings given in the second and subsequent arguments are concatenated with a delimiter.

length

To get the length of the string, use length function.

$ret = length $str;

substr

Use substr function to extract and replace the characters at the specified position.

[A] Extract the character at the specified position

$ret = substr($str, 2, 4);

The first argument is the target string. The second argument is the start position of the string you want to extract. The third argument is the length of the string you want to extract.

[B] Replace the string at the specified position

substr($str, 0, 2, $replace);

To replace the string at the specified position, specify the replaced string in the 4th argument. In this example, the first two characters of $str are replaced by $replace.

index

Use index function to search for a string.

$ret = index($str, $search);

In the first argument, specify the string to be searched, and in the second argument, specify the string you want to search. The position where the string is found is returned as the return value. If not found, -1 will be returned.

$ret = index($str, $search, $pos);

You can specify the search start position in the third argument.

rindex

Use rindex function to search for a string from the end of the string.

$ret = rindex($str, $search);

split

Use split function to split the string by the delimiter.

@ret = split(/,/, $str);

Specify the delimiter as a regular expression in the first argument. In the second argument, specify the string you want to split. The return value is an array of split strings.

reverse

Use reverse function to reverse the order of the strings.

$ret = reverse $str;

Also, when used on an array, the reverse function reverses the order of the array.

uc

Use uc function to convert the string to uppercase.

$ret = uc $str;

ucfirst

Use ucfirst function to convert only the beginning of a string to uppercase.

$ret = ucfirst $str;

lc

Use lc function to convert the string to lowercase.

$ret = lc $str;

lcfirst

Use lcfirst function to convert only the beginning of a string to lowercase.

$ret = lcfirst $str;

sprintf

Use sprintf function to create a formatted string.
$ret = sprintf($format, @strs);

The first argument is a string that represents the format. The second and subsequent arguments are the strings embedded in the format specifier part.

[A] Formatting example

Interpret $num as an integer and format it with 8 digits. Parts less than 8 digits are padded with 0s.

$ret = sprintf("%08d", $num);

Interpret $num as a floating point and round it to two decimal places.

$ret = sprintf("%.2f", $num);

[B] List of format specifiers

%c Convert numbers to characters corresponding to ASCII code
Interpret the%s argument as a string
Interpret the%d argument as a signed integer
Interpret the%u argument as an unsigned integer
%o Convert positive numbers to octal strings
%x Convert positive numbers to hexadecimal strings (lowercase notation)
%X Convert positive numbers to hexadecimal strings (uppercase)
%b Convert positive numbers to binary strings
Interpret the%f argument as a floating point
Interpret%e argument as floating point(formatted in exponential notation (lowercase))
Interpret%E argument as floating point(formatted in exponential notation (uppercase))
Interpret%g argument as floating point(formatted in exponential notation (lowercase), trailing 0s removed)
Interpret the%G argument as a floating point number (finger)Formatted in number notation (uppercase). The trailing 0 is removed)
Translated to the in-memory address of the variable given in the%p argument

chomp

Use chomp function to remove the trailing line break.

chomp $str

Quart operator "q"

If you want to use single quotes without escaping them, use quote operator.

q (aaa'bbb)

The function is the same as when enclosed in single quotes. No variable expansion is done.

# Same as this
'aaa \'bbb'

Double quote operator "qq"

If you want to use double quotes without escaping them, use double quote operator.

qq (aaa "bbb)

The function is the same as when enclosed in double quotes. Variable expansion is performed.

# Same as this
"aaa \" bbb "

quotemeta

Use quotemeta function to escape special strings used in a regular expression.

$ret = quotemeta $str;

chr

Use chr function to convert a number to the corresponding ASCII character.

$ret = chr $num;

ord

Use ord function to convert ASCII code characters to numbers, which is an internal representation.

$ret = ord $char;

oct

Use oct function to convert an octal string to the corresponding number.

$ret = oct $octal;

hex

Use hex function to convert a hexadecimal string to the corresponding number.

$ret = hex $hex;

3 Array manipulation

Get the number of arrays

To get the number of arrays, evaluate the arrays in scalar context.

$ret = @array;

Last index in the array

Use $# array to get the last index of the array.

$ret = $# array;

shift

Use shift function to retrieve the first element of the array.

$ret = shift @array;

unshift

Use unshift function to add an element to the beginning of the array.

unshift(@array, @items);

pop

Use pop function to retrieve the last element of the array.

$ret = pop @array;

push

Use push function to add an element to the end of the array.

push(@array, @items);

splice

Use splice function to work with multiple elements on an array.

[A] Extract multiple elements

You can retrieve multiple elements.

@ret = splice(@array, $pos, $size)

Specify the target array in the first argument, the start position in the second argument, and the size you want to extract in the third argument.

[B] Replace multiple elements

You can replace multiple elements.

splice(@array, $pos, $size, @items);

Specify the array you want to replace with the 4th argument.

Array slice

Use Array Slice to get multiple elements from an array.

@ret = @array[0, 1, 3];

In this example, the 0th, 1st, and 3rd elements of @array are assigned to @ret.

grep

If you want to retrieve only the elements that match the conditions, use grep function.

@ret = grep {condition} @array;

This is an example to extract a value greater than 3.

@ret = grep {$_ > 3} @array;

The elements of the array are sequentially assigned to $_. Only those that satisfy $_ > 3 will be assigned to @ret.

map

Use map function to process all the elements of the array.

@ret = map {element manipulation} @array;

This is an example that doubles all the elements.

@ret = map {$_ * 2} @array;

The elements of the array are sequentially assigned to $_. The result of $_ * 2 is assigned to @ret.

max (List::Util)

To find the maximum value of an array element, use the max function of List::Util module.

use List::Util 'max';
$ret = max @array;

min (List::Util)

To find the minimum value of an array element, use the min function of List::Util module.

use List::Util 'min';
$ret = min @array;

sum (List::Util)

Use the sum function of List::Util module to sum the elements of the array.

use List::Util 'sum';
$ret = sum @array;

sort

Use sort function to sort the elements of the array.

@ret = sort {sorting conditions} @array;

[A] Compare numerically and sort in ascending order

This is an example that compares numerically and sorts in ascending order.

@ret = sort {$a <=> $b} @array;

Use <=> to compare numerically. To sort in ascending order, use $a <=> $b.

[B] Compare numerically and sort in descending order

This is an example that compares numerically and sorts in descending order.

@ret = sort {$b <=> $a} @array;

Use <=> to compare numerically. To sort in descending order, use $b <=> $a.

[C] Compare in dictionary order and sort in ascending order

This is an example that compares in dictionary order and sorts in ascending order.

@ret = sort {$a cmp $b} @array;

Use cmp to compare in lexicographical order. If you want to sort in ascending order, use $a cmp $b.

[D] Compare in dictionary order and sort in descending order

This is an example that compares in dictionary order and sorts in descending order.

@ret = sort {$b cmp $a} @array;

Use cmp to compare in lexicographical order. If you want to sort in descending order, use $b cmp $a.

shuffle (List::Util)

To sort the array randomly, use the shuffle function of List::Util module.

use List::Util 'shuffle';
@ret = shuffle @array;

reverse

Use reverse function to reverse the elements of the array.

@ret = reverse @array;

String list operator

You can use string list operator to represent a list of strings without commas or quotes.

@array = qw(cat dob mouse);

4 Hash operation

keys

Use keys function to get all the keys in the hash.

@ret = keys %hash;

values

To get all the values of a hashUse values function.

@ret = values %hash;

each

Use each function to get the hash key/value pairs in sequence.

($key, $value) = each %hash;

Use while statement to process all key/value pairs in sequence.

while (my ($key, $value) = each %hash) {
  ...
}

exists

Use exists function to check for the existence of the hash key.

$ret = exists($hash{$key});

delete

Use delete function to delete the hash key.

delete $hash{$key};

reverse

Use reverse function to swap the hash key and value.

%ret = reverse %hash;

5 File input/output

open

Use open function to open the file.

open(my $fh, "<", $file)
  or die "Cannot open $file:$!";

If the file is opened successfully, the file handle is assigned to $fh. (Declaring $fh and passing it to the open function at the same time.)

It is necessary to handle the error when the file open fails.

[A] Open mode

A list of commonly used open modes.

Read <
Write>
Additional writing >>

close

Use close function to close the file handle.

close $fh;

File input operator

Use file input operator to read a line from a file.

$line = <$fh>;

Usually used with while statement.

while (my $line = <$fh>) {
  ...
}

[A] Read all rows into an array

Use the diamond operator in the list context to read all rows into the array.

@lines = <$fh>;

fileno

Use fileno function to get the file descriptor.

$ret = fileno $fh;

opendir

Use opendir function to open the directory.

opendir(my $dh, $dir)
  or die "Cannot open $dir:$!";

The opened directory handle is assigned to $dh. It is necessary to handle the error when the directory open fails.

closeddir

Use closedir function to close the directory handle.

closedir $dh;

readdir

Use readdir function to read the filenames in the directory one by one.

$file = readdir $dh;

Usually used with while statement.

while (my $file = readdir $dh) {
  ...
}

6 File/directory operations

unlink

Use unlink function to delete the file.

unlink $file
  or die "Cannot remove $file:$!";

copy (File::Copy)

To copy a file, use the copy function of File::Copy module.

use File::Copy 'copy';
copy ($file_from, $file_to)
  or die "Cannot copy $file_from to $file_to:$!";

move (File::Copy)

To move a file, use the move function of File::Copy module.

use File::Copy 'copy';
move ($file_from, $file_to)
  or die "Cannot move $file_from to $file_to:$!";

chdir

To change the current directory, get chdir function.

chdir $dir
  or die "Cannot change directory $dir:$!";

mkdir

Use mkdir function to create the directory.

mkdir $dir
  or die "Cannot create directory $dir:$!";

rmdir

Use rmdir function to delete the directory.

rmdir $dir
  or die "Cannot remove directory $dir:$!";

mkpath(File::Path)

To create a multi-level directory, use the mkpath function of File::Path module.

use File::Path 'mkpath';
eval {
  mkpath $dir
};

if ($@) {
  die "Cannot create $dir: $@";
}

If mkpath fails, an exception will be thrown, so catch it with the eval block. The content of the error when an exception occurs is stored in $@.

rmtree(File::Path)

If you want to delete the directory that contains the files inside, use the rmtree function of File::Path module.

use File::Path 'rmtree';

rmtree($dir, {error =>\my $errors});
for my $diag (@$errors) {
  my ($file, $message) = each %$diag;
  warn "problem unlinking $file: $message\n";
}

In the first argument, specify the directory you want to delete. You can specify options for the last argument. In this example, I am trying to get the content of the error.

getcwd (Cwd)

To get the current directory, use the getcwd function of Cwd module.

use Cwd 'getcwd';
$ret = getcwd;

chmod

Use chmod function to change the file permissions.

chmod($permission, $file)
  or die "Cannot change permission $file:$!";

basename(File::Basename)

To retrieve the base name of a file, use the basename function of File::Basename module.

use File::Basename 'basename';
$ret = basename $file;

If the file name is /a/b/c.txt, c.txt is the base name.

dirname(File::Basename)

To get the name of the directory that contains the file, use the dirname function of File::Basename module.

use File::Basename 'dirname';
$ret = dirname $file;

In the case of the file name /a/b/c.txt,/a/b corresponds to the directory name.

FileStrike operator

You can use file test operator to check the existence of a file or directory.

# Check the existence of normal files
$ret = -f $file;

# Check the existence of the directory
$ret = -d $dir;

Usually used with conditional statement.

if (-f $file) {
  ...
}

[A] List of commonly used file operators

-e Check if the file exists(including the directory)
-f Check if the file is a regular file
-d Check if the directory exists
-r Check if it can be read
-w Check if writable
-x Check if it is executable
-M Get the number of days that have passed since the last update
-A Get the number of days that have passed since the last access
-s Get phi size (unit is bytes)

7 Time/Time

time

Use time function to get the elapsed seconds from the epoch to the present.

$ret = time;

The epoch time is January 1, 1970.

localtime

Use localtime function to get the current date and time.

($sec, $min, $hour, $mday, $mon, $year, $wday) = localtime;
$year += 1900;
$mon += 1;

From the beginning, the order is "seconds, minutes, hours, days, months, years, days of the week". The year is an elapsed year from 1900, so you need to add 1900 to the year you got it. Months start at 0, so you need to add 1 to get the actual month.

timelocal (Time::Local)

To get the elapsed seconds since the epoch from the date and time information, use Time::Local module's timelocal function.

use Time::Local 'timelocal';
$ret = timelocal ($sec, $min, $hour, $mday, $mon, $year);

sleep

Use sleep function to sleep. The sleep time is specified in seconds.

sleep $sec;

When it sleeps, the program will stop during that time.

usleep(Time::HiRes)

To sleep in microseconds, use the usleep function of Time::HiRes module.

use Time::HiRes 'usleep';
usleep $microsec;

8 Other important functions

defined

Use defined function to see if the value is defined.

$ret = defined($val);

kill

Use the kill function to signal the process.

kill($signal_number, $child_process_id);

caller

Use the caller function to get information about the calling function.

($package, $filename, $line, $subroutine) = caller(0);

In the argument, specify how many layers the caller information should be got. The return value will be the package name, file name, line number, and subroutine name in that order.

getpwuid

Use getpwuid function to get the execution username.

$ret = getpwuid($>);

Specify the user ID in the first argument. The execution user ID is stored in a predefined variable called $>, so specify this.

hostname (Sys::Hostname)

To get the hostname, use the hostname function in Sys::Hostname module.

use Sys::Hostname 'hostname';
$ret = hostname;

die

Use die function to display an error message and exit the program.

die $message;

warn

Use warn function to display the warning message.

warn $message;

eval block

Use the eval block to catch exceptions. (See Exception Handling)

eval {
  Processing that may cause an exception
};

if ($@) {
  What to do if an exception occurs
}

If an exception occurs, the content of the error is set in $@.

__PACKAGE__

You can get the current package name with __PACKAGE__.

$ret = __PACKAGE__;

__LINE__

You can get the line number on the script with __LINE__.

$ret = __LINE__;

__FILE__

You can get the script file name with __FILE__.

$ret = __FILE__;

9 How to look up function and module documentation

Function documentation

perldoc -f function name

You can see it at.

The module documentation is

perldoc module name

You can see it at.

If you want to output the document to a file, you can use redirection.

perldoc -f function name> file name

10 Frequently used predefined variable

$. Line number of the file being read
$$Process ID
$> Execution user ID
$) Execution group ID
$0 Name of the program being executed
$^O OS name
$^T Time when the program started
@INC module search path
%INC Information on loaded modules
%ENV environment variable
%SIG signal handler
@ARGV command line arguments
@_ Subroutine arguments
$! OS error
$@Eval error

11 Frequently used modules

File::Spec

You can use File::Spec module to create a file name according to the OS.

use File::Spec;
my $file_name = File::Spec->catfile('dir', 'file.txt');

On Windows operating systems, $file_name is dir\file.txt, and on Unix operating systems, the file name is dir/file.txt.

FindBin

You can use FindBin module to get the name of the directory where the script you are running is located.

use FindBin;
my $script_dir = $FindBin::Bin;

$FindBin::Bin contains the name of the directory where the script you are running is located.

lib

You can add a module search path using lib module.

use lib qw /. lib/;

This is an example of adding the current directory and the lib directory of the current directory to the module search path.

Carp

Use Carp module to report an error from the caller's perspective. Use croak instead of die and carp instead of warn.

use Carp qw/croak carp/;

# Same as die
croak ($message);

# Same as warn
carp ($message);

Get::Options

If you want to receive options with command line arguments, use Get::Options module To use. For example, suppose you want to receive the following options:

perl script_name - length = 100 - file = test.txt - verbose

To receive this option, write:

use Getopt::Long 'GetOptions';

# Set default value
my $data = 'file.dat';
my $length = 24;
my $verbose;

# Receive value from command line option
# (Numeric value,String, boolean value)
GetOptions(
  'length = i'=> \$length,
  'file = s'=> \$data,
  'verbose' => \$verbose
);

URI

Use the URI module to handle URL operations conveniently.

use URI;

my $url = URI->new('http://www.perl.com/index.html');

# URL schema name http
my $schema = $url->schema;

# URL host name www.perl.com
my $host = $url->host;

# URL path part /index.html
my $path = $url->path;

# URL query string settings
$url->query_form(name =>'taro', age => 13);

# URL query string name = taro & age = 13
my $query = $url->query;

# Get URL as a string http://www.perl.com/index.html?name=taro&age=13
my $url_str = $url->as_string;

Data::Dumper

Use Data::Dumper module to output the contents of an array or hash.

use Data::Dumper;
my $hash = {a => 1, b => 2};
print Data::Dumper->Dump([$hash], ['$hash']);

XML::Simple

Use XML::Simple module to convert XML to a Perl data structure.

use XML::Simple;
my $xml = XML::Simple->new;
my $hash = $xml->XMLin($xml_file);

You can parse an XML file with the XMLin method and convert it to a Perl data structure.

LWP::UserAgent

Use the LWP::UserAgent module to get information from the internet.

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $response = $ua->get($url);

my $content; # Obtained content
if ($response->is_success) {
  $content = $response->content;
}
else {
  die($response->status_line);
}

Get the URL of the page you want to get in the get method. An HTTP::Response object will be returned, so check if the is_success method succeeded. If successful, get the content of the page obtained by the content method.

Net::FTP

If you want to do FTP, use Net::FTP module.

use Net::FTP;

# Specify the host name (or IP address) to connect to the FTP server
my $ftp = Net::FTP->new($host)
  or die "Cannot connect to $host: $@";

# Login by specifying user name and password
$ftp->login($user, $password)
  or die "Cannot login", $ftp->message;

# Change current directory
$ftp->cwd($dir)
  or die "Cannot change working directory", $ft

# Get file
$ftp->get($file)
  or die "get failed", $ftp->message;

# FTP disconnection
$ftp->quit;

Text::Diff

If you want to check the difference between files, use Text::Diff module.

use Text::Diff 'diff';
my $diff = diff ($file1, $file2);

Related Informatrion