Hatena::ブログ(Diary)

Perl5 Guides for perl newbie RSSフィード

  Perl5 guides, following modern perl syntax after Perl 5.8.1. (Japanese)

2010-11-07

Perl Tutorial

f:id:perlcodesample:20100925184455j:image

 This is Perl tutorail. If you have known other languages, You can learn basic syntax of Perl from this tutorial easily and write Perl soon.

1. Basic

Check syntax

To check syntax strictly, write the following two lines.

use strict;
use warnings;

You write source code fast and improve the quality of it because these two lines enable compile-time syntax checking.

print

Print the output to the display.

print "Hello world";

You don't always have to use parentheses "()" in Perl.

Comment

 Comment.

# Comment
Variable declaration

Perl has three variable type, scalar, arrays, and hashes.

# Scalar
my $num;

# Arrays
my @students

# Hashes
my %month_num;
Run the script

To run the script, use perl command.

perl script.pl

To write output to the file, use redirect.

perl script.pl > file.txt
Check the syntax in compile-time

To check the syntax in compile-time, use -c option

perl -c script.pl
Run Perl debugger

To run the Perl debugger, use -d option.

perl -d script.pl

About debugger, See also Perl Debugger

2. Number

The expression of number

You can assign a number to scalar variable. You can assign integer and decimal as the number. To split the big number, use under bar "_" .

my $num = 1;
my $num = 1.234;
my $num = 100_000_000;
Numeric operations

Numeric operations

$num = 1 + 1;
$num = 1 - 1;
$num = 1 * 2;
$num = 1 / 2;

Integer part of division and remainder. To calculate integer part of division, use int function after division.

# Integer part of division
$div = int(3/2);

# Remainder
$mod = 3 % 2;
Increment and decrement

Increment and decrement.

# Increment
$i++

# Decrement
$i--

3. String

The expression of string

String is surrounded by single-quote or double-quote. In double-quote, you can use special charactor like \t(Tab) or \n(line break). In double-quote, a variable is expanded to the string.

my $str1 = 'abc';
my $str2 = "def";
my $str3 = "a\tbc\n";

# Variable expansion (the result is 'abc def')
my $str4 = "$str1 def";
String operations

 String operations.

# Join
my $join1 = 'aaa' . 'bbb';

my $join2 = join(',', 'aaa', 'bbb', 'ccc');

# Split
my @record = split(/,/, 'aaa,bbb,ccc');

# Length
my $length = length 'abcdef';

# Cut
my $substr = substr('abcd', 0, 2); # ab

# Search
my $result = index('abcd', 'cd'); # Return value is the position the string is found or -1 if not found.

4. Array

Declaration and assignment of a array

Declaration and assignment of a array. Array is variable which have multiple values.

# Declaration of a array
my @array;

# Assign values to a array
@array = (1, 2, 3);
Get and set the element of a array

 Get and set the element of a array

# Get a element
$array[0];
$array[1];

# Set a element
$array[0] = 1;
$array[1] = 2;
Count of elements of a array

To get the count of elements of array, evaluate the array in scalar context. This is a little strange syntax in Perl.

my $array_num = @array;
Manipulation of a array

The function to manipulate a array.

# Cut off the first element of array.
my $first = shift @array;

# Insert a element to the head of array
unshift @array, 5;

# Get the last value of array
my $last = pop @array;

# Insert a element to the tail of array
push @array, 9;

5. Hash

Declaration and assignment of hash

Declaration and assignment of hash. hash is a variable which have pairs of key and value.

my %hash;
%hash = (a => 1, b => 2);
Get and set the value of hash

Get and set the value of hash.

# Get a value of hash
$hash{a};
$hash{b};

# Set a value of hash
$hash{a} = 5;
$hash{b} = 7;

 If the key of hash is consist of "a-zA-Z_", You don't have to surround the key by single quote or double auote.

Functions related to hash
# Get the all keys of hash
@keys = keys %hash;

# Get the all values of hash
@values = values %hash;

# Check the existence of a key
exists $hash{a};

# Delete the key of hash
delete $hash{a};

6. Control structures

if

 if.

if (condition) {
    
}
if 〜 else

 if 〜 else.

if (condition) {
    
}
else {
    
}
if 〜 elsif

 if 〜 elsif.

if (condition1) {
    
}
elsif (condition2) {
    
}

 Note that this is "elsif", not "else if".

while

 while.

my $i = 0;
while ($i < 5) {
    
    # Do something
    
    $i++;
}
for

 for.

for (my $i = 0; $i < 5; $i++) {
    
}
foreach文

 foreach. Process all elements of array. many people prefer "foreach" rather than "for" in Perl.

foreach my $field (@fields) {
    
}

foreach is alias of for.

Comparison operator

 The list of comparison operator. In perl, number comparison is different from string comparison.

[A]Number comparison operator

$p == $q$p is equal to $q
$p != $q$p is not equal to $q
$p < $q$p is lower than $q
$p > $q$p is bigger than $q
$p <= $q$p is lower than or equal to $q
$p >= $q$p is bigger than or equal to $q

[B]String comparison operator

$s eq $t$s is equal to $t
$s ne $t$s is not equal to $t
$s lt $t$s is lower than $t
$s gt $t$s is bigger than $t
$s le $t$s is lower than or equal to $t
$s ge $t$s is bigger than or equal to $t

7. Subroutine

Function in other language is called subroutine in Perl. To define subroutine, do the following way.

sub sum {
    my ($num1, $num2) = @_;
    
    my $total = $num1 + $num2;
    
    return $total;
}

You don't have to specify name of arguments in Perl. the array named @_ countains the arguments. To return a return a value, use return

8. File I/O

 File I/O.

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

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

close $fh;

 If you open a file by open function, File handle is assigned to $fh. '<' is read mode. If you open a file write mode, use '>'. the statement after or is executed when the file opening fail. die is the function to exit the script with error message. $! is error message from the operation system.

Well known syntax

The list of well known syntax in Perl.

True and false value

False value is the following ones.

  • undef
  • ''
  • 0
  • '0'

True value is all other values.

defined

 To check the value is defined, use defined function

defined $num;
Command line argument

 To receive command line arguments, use @ARGV。

my ($file, $options) = @ARGV;

 If you want to receive only one argument, do the following way. @ARGV is passed to the argument of shift implicitly.

my $file = shift;
Scalar context and list context

 Sometime the return value of function is different in the context. For example, localtime function.

# Scalar context (Return value is string of date/time)
my $time_str = localtime();

# List context (Return value is array of date/time informations)
my @datetime = localtime();
unless

unless is reverse of if.

unless (condition) {
    
}
Post located if, Post located unless

 if or unless can be located after the statement.

# Post located if
print $num if $num > 3;

# Post located unless
die "error" unless $num;
Array slice and hash slice

If you use array slice or hash slice, get the specified element as a array.

# Array slice
@select = @array[1, 4, 5];

# Hash slice
@select = @hash{'a', 'b', 'd'};
map

If you use map function, convert each elements of array. Each elements is assigned to $_ in order.

@mapped = map { $_ * 2 } @array;
grep

 If you use grep function, Get only elements matching the condition. Each elements is assigned to $_ in order.

@select = grep { $_ =~ 'cat' } @array;
List assignment

The following is list assignment.

my ($num1, $num2) = ($num3, $num4);
Range operator

To specify the range of integer, use range operator.

my @numes = (0 .. 5);
String list operator

You can write string list easily.

my @strs = qw/aaa bbb ccc/;
return without argumnets

If you write return without arguments, in scalar context undef is returned undef, in list context empty list is returned. If you tell the error by using return value, write "return", not write "return undef".

sub name {
    my @args = @_;
    
    return;
}

Exception handling

To throw an exception, use die function.

die "Error message";

To catch the exeption, surround the statement by eval, and check $@.

eval { STATEMENT };

if ($@) {
    
}
Read all lines from a file

The function to read all lines is not exists. Join the all line after reading all lines to array.

my @lines = <$fh>;
my $content = join '', @lines; 

One line.

my $content = join '', <$fh>;
Ternary operator

Ternary operator. In the following example, if $flg is true, 1 is assigned to $num, if not, 2 is assigned to $num.

my $num = $flg ? 1 : 2;
||=

If left value is false, right value is assigned. In the following example, if $num is false, 2 is assigned to $num.

$num ||= 2; 
Load module

To load a module, use use function.

use MODULE;


2010-11-05

All Guides

All articles of "Perl5 Guides for perl newbie"

Tutorials

  1. What is Perl? - Description of Perl features
  2. Perl Installation - The way to install Perl

2010-11-02

Perl Installation

http://www.activestate.com/activeperl

In Unix or Linux Perl is installed by default. In these OS you don't have to install Perl. In Windows you need Perl installation.

It is easy to install Perl on Windows. You can use ActivePerl, which is configured for Windows. ActivePerl is provided by ActiveState for free.

Downloading ActivePerl

Download ActivePerl(#1)。

Donloading pageActivePerl 5.12.2.1202

Installation of ActivePerl

Try to install ActivePerl. You double-click the donwnloaded file. Installer is openned. You continue to click the "next" button. Installaition will be finished.

After the installation, try to check the success of the installation. Run command prompt and show the version of Perl. You can execute command prompt by this step, "Start" -> "All programs" -> "Accessories" -> "Command prompt"

# Show the version
perl -v

 Installation success if the following version information is shown.

This is perl, v5.12.2 built for MSWin32-x86-multi-thread
(with 2 registered patches, see perl -V for more detail)

You finished Perl installation.

Note

#1 The popup to subscribe News Letter is shown. You don't have to do it if you don't hope. The "msi" extension is the one of Windows installer. The link is ActivePerl for 32bit Windows. If you use 64bit Windows, download ActivePerl for 64bit Windows.