Hatena::ブログ(Diary)

Perl Tutorial by Code Examples

2009-12-26

Master Perl Basic Syntax Quickly

I introduce Perl basic syntax. If you already learn other language, this entry help you learn Perl basic syntax and write Perl in a short time.

Basic

Syntax checking

You should write these 2 line at the start to check syntax strictly.

use strict;
use warnings;

If you write these 2 line, syntax checking is done before execution, so your coding speed is up, and increase source code quality.

print statement

print statement.

print "Hello world";

In Perl you can omit parentheses in standard functions or function which is defined beforehand.

Comment

Comment:

#  comment 
Variable declaration

Variable declaration: There are scalar variable, array variable, hash variable.

# Scalar variable 
my $num;

# Array variable 
my @students

# Hash variable 
my %month_num;
Execute script

script execute command line in as below.

perl script.pl

output result file write output redirect use .

perl script.pl > file.txt
Compile-time checking

You can do compile-time syntax checking from command line.

perl -c script.pl
Debugger starting

You can start debugger from command line.

perl -d script.pl

See also Debugger Manual about debugger.

Number

Number representation

You assign number to scalar variable. Both integer and decimal can be assigned. You can use underscore as separating character when digit is large.

my $num = 1;
my $num = 1.234;
my $num = 100_000_000;
Four arithmetic operations

Four arithmetic operations.

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

Remainder and quotient calculation. If you want to calculate quotient, after you do usual division, extract integer part by int function.

# Quotient 
$div = int(3/2);

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

Increment and decrement.

# Increment 
$i++

# Decrement 
$i--

String

String representation

String is surrounded by single quote or double quote. In double quote, you can use special character such as \t(tab) or \n(line break), and you also you can do variable expansion.

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

# Variable expansion (Result is abc def)
my $str4 = "$str1 def";
String operation

Various string operation.

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

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

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

#  length 
my $length = length 'abcdef';

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

#  search 
my $result = index('abcd', 'cd'); # If found, the position is returned. If not, -1 is returned.

Array

Array declaration and assignment

array declare and assignment . array multiple value assignment can variable .

#  array declare 
my @array;

#  array to assignment 
@array = (1, 2, 3);
Array element get and assignment

Get and assign array element.

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

# Assign element
$array[0] = 1;
$array[1] = 2;
Array elements count

If you want to get array elements count, you evaluate array in scalar context. This is a little special syntax which is seen in only Perl.

my $array_num = @array;
Array operations

Array operating functions.

# Get fisrt element
my $first = shift @array;

# Add element to first
unshift @array, 5;

# Get last element
my $last = pop @array;

# Add element to last
push @array, 9;

Hash

Hash declaration and assignment

Hash declaration and assignment. Hash is a variable which contains multiple key and value pairs.

my %hash;
%hash = (a => 1, b => 2);
Get and assign hash element

Get and assign hash element.

# Get element
$hash{a};
$hash{b};

# Assign element
$hash{a} = 5;
$hash{b} = 7;

If hash key is consist of "a-zA-Z_", key don't have to be surrounded by single quote or double quote.

Hash related functions
# Get keys 
@keys = keys %hash;

# Get values
@values = values %hash;

# Check key existence
exists $hash{a};

# Delete hash key
delete $hash{a};

Control statement

if statement

if statement.

if (Condition) {
  
}
if 〜 else statement

if 〜 else statement.

if (Condition) {
    
}
else {
    
}
if 〜 elsif statement

if 〜 elsif statement.

if (Condition) {
    
}
elsif (Condition) {
    
}

Note "elsif", not "else if" such as other languages.

while statement

while statement.

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

for statement.

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

foreach statement. You can iterate array all elements. foreach is alias of for. foreach is exactly same as for.

foreach my $field (@fields) {
  ...
}
Comparison operators

Comparison operators. In Perl, number comparison is different from string comparison.

[A] Number compararigon operators

$p == $q$p$q equal
$p != $q$p$q equal not
$p < $q$p$q smaller
$p > $q$p$q bigger
$p <= $q$p$q the following
$p >= $q$p$q not less

[B] String comparison operators

$s eq $t$s$t equal
$s ne $t$s$t equal not
$s lt $t$s$t smaller
$s gt $t$s$t bigger
$s le $t$s$t the following
$s ge $t$s$t not less

7. Subroutine

In Perl, function is also called subroutine. You can create subroutine as the following.

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

In Perl unlike other language, you don't have to specify arguments explicitly. Arguments is assigned to array @_. If you want to return value, use return.

File IO

File IO.

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

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

close $fh;

If you open file by open function, file handle is assigned to $fh. '<' is reading mode. If you want to write to file, you can use '>'. statement after "or" is executed when file open fail. die is function to display error message and exit program. OS error message when file open fail is assigned to $!.

Syntax you should learn

List of Perl syntax which you may see in many source codes.

True and false values in Perl

The following is Perl false values.

undef # undefined
''    # empty string
0     # zero
'0'   # string zero
()    # empty list or array

All values except these are true values.

Check the value is defined

You can use defined function to check the value is defined.

defined $num;
Command line arguments

You can use @ARGV variable to receive command line arguments.

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

If you receive only one argument, you can also write in the following. Implicitly @ARGV is passed to shift function arguments.

my $file = shift;
Scalar context and list context

In Perl, there are functions which return different values in different context. localtime function is one example.

# Scalar context (Get date and time as string)
my $time_str = localtime();

# List  context (Get date and time as array elements)
my @datetime = localtime();
unless statement

unless represent opposite of if statement.

unless (Condition) {
  ...    
}
Write if or unless after statement

In perl, you can write if or unless after statement.

# Write if after statement
print $num if $num > 3;

# Write unless after statement
die "error" unless $num;
Write for after statement

In perl, you can write for after statement.

# Write for after statement
print $_ for @nums;

each value is assigned to $_ in order.

Array slice and hash slice

You can get only specified elements if you use array slice or hash slice.

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

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

You can convert all values in array by map function. Each element of array is assigned to $_ in order.

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

You can get only condition matched elements if you use grep function. Each element of array is assigned to $_ in order.

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

You can use list assignment.

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

You use range operator to represent integer range.

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

Syntax to write string list easily.

my @strs = qw/aaa bbb ccc/;
Single return

If you write single return, if context is scalar context, undef is returned, if context is list context, empty list () is returned. Usually if you inform error occur in subroutine, you write "return", not "return undef".

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

You can use die function to throw exception.

die "Error message";

You can chatch exception by eval. You can check exception by $@.

eval { (process exception occur.) };

if ($@) {
  ...
}
Read all contents from file

Perl don't have function to read contents from file, so you can read lines to array and join it by empty string.

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

You can also write this by one line.

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

Ternary operator . In the following example, If $flg is true, 1 is assigned to $num, if $flg is false value, 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 value, 2 is assigned to $num.

$num ||= 2; 
//=

Defined-or operator. If left value is undefined, right value is assigned. In the following example, if left value is undefined, 2 is assigned to $num.

$num //= 2; 
Load module

You can use use to load module.

use MODULE_NAME;
Write configuration file by Perl

You can use do function to read configuration file written by Perl.

my $conf_file = "app.conf";
my $conf = do $conf_file
  or die qq/Can't load config file "$conf_file": $!$@/;

The following is config file content.

{
  name => 'Foo',
  number => 9
}

If file reading or parsing fail, undef is returned. If file is not exists, error message is assigned to $!. If file loading fail, error message is assigned to $@.

Multiple lines comment

You can write Multiple lines comment

=pod

Comment 1
Comment 2

=cut


Table of contents

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証

トラックバック - http://d.hatena.ne.jp/perlcodesampleen/20091226/1264257759