29 April 2011

Logical Operator





&& ถ้าหากด้านซ้ายเป็นจริงจะทำงานด้านขวา

|| ถ้าด้านซ้ายเป็นเท็จจะทำงานด้านขวา
// ถ้าด้านซ้ายไม่ได้กำหนดค่าทำด้านขวา

ตัวอย่าง

$x = 0;
$y = $x && 5;
$y จะมีค่าเท่ากับ 0

$x = 1;
$y = $x && 5;
$y จะมีค่าเท่ากับ 5

$x = 0;
$y = $x || 5;
$y จะมีค่าเท่ากับ 5

$x = 20;
$y = $x || 5;
$y จะมีค่าเท่ากับ 20

$y = $x // 5;
$y จะมีค่าเท่ากับ 5

String Operator

การเชิื่อม string กับ ตัวแปร
print "string".$x."=".$y."\n";

print repeat
print "-" x 20;
ผลลัพธ์จะได้ - ต่อกัน 20 อัน

Syntax Condition Test

Test Condition,Excute Code
if($x >= 0){
print "x is positive number\n";
}

Defind code,Test Condition,Excute
print "x is positive number\n" if($x >= 0);

Excute code,Test Condition,Excute Code
($x >= 0) && print "x is positive number\n";

28 April 2011

hash variable

ตัวแปร hash ใน perl จะขึ้นต้นด้วย % ซึ่งสามารถกำหนดค่าโดย

%hash = (key1,value1,key2,value2,.....);

%hash = (key1 => value1,key2 => value2,...);

การแสดงค่าของ hash

$hash{key};

แสดงเฉพาะ key ที่อยู่ใน hash

@allKey = keys %hash;

แสดงเฉพาะ value ที่อยู่ใน hash

@allValue = values %hash;

loop hash

while(keys %hash){
print $_."=".$hash{$_};
}

for(values %hash){
print $_;
}

array in perl

array ใน perl จะใช้เครื่องหมาย @ นำหน้าตัวแปร

@array = (value1,value2,value3,...);

โดยสามารถแสดงค่าของแต่ละ index โดยใช้

$array[number]; # number หมายถึงตัวเลขของ index เริ่มจาก 0

function ที่ใช้กับอาเรย์

push(@array,value); #เพิ่มข้อมูลเข้าไปยังท้ายสุดของอาเรย์
pop(@array); #ลบข้อมูลท้ายสุดของอาเรย์
unshift(@array,value); #เพิ่มข้อมูลไปที่ index 0
shift(@array); #ลบข้อมูลที่ index 0
delete($array[index]);

การนับจำนวนของ array
scalar(@array);
$#array+1; #เป็นการหาค่า index ตัวสุดท้ายของ อาเรย์ ถ้านำมาบวก 1 คือจำนวนอาเรย์ทั้งหมด

foreach ของ array

foreach(@array){
print $_;
}

foreach(0..$#array){
print $array[$_];
}

แสดงค่าตำแหน่งของข้อมูลที่เก็บบน memory

#!c:\perl\bin\perl.exe

use strict;
use CGI;

my $cgi = CGI->new;
print $cgi->header("text/html");

my $data = "myData";
my $ref = \$data; #$ref จะเก็บค่าตำแหน่งของ $data
print $ref."<br>"; # แสดงค่าตำแหน่ง
print $$ref."<br>"; #ใช้ค่าของตำแหน่งแสดงข้อมูลที่ตำแหน่งนั้น
print ${$ref}; #แสดงข้อมูลที่ตำแหน่งนั้น

declare scalar variable

ประกาศแบบไม่กำหนดค่าเริ่มต้นให้
my $scalar;

ประกาศแบบกำหนดค่าเริ่มต้นให้
my $scalar = value;

ประกาศแบบหลายตัวแปร
my($scalar1,$scalar2,.....) = (value1,value2,....);