Upload
pierce-webb
View
224
Download
0
Embed Size (px)
Citation preview
COMP519: Web ProgrammingAutumn 2007
Perl Tutorial: Beyond the Basics Keyboard Input and file handling
Control structures
Conditionals
String Matching
Substitution and Translation
Split
Associative arrays
Subroutines
References
Keyboard Input
بعنوان STDIN از Perlدر ورودی استاندارد پیش
فرض)به صورت یک دستگیره فایل( یا همان صفحه کلید استفاده می
گردد.
$new = <STDIN;>
اگر ورودی رشته باشد ما n\معموال می خواهیم که
آخر رشته حذف شود. برای اینکار می توانیم از تابع
chomp به یکی از روشهای زیر استفاده کنیم:
chomp($new = <STDIN>);
یا $new = <STDIN;> chomp($new);
#!/usr/local/bin/perl
# basic08.pl COMP519
print "Please input the circle’s radius: ";
$radius = <STDIN>;
$area = 3.14159265 * $radius * $radius;
print "The area is: $area \n";
bash-2.05b$ perl basic08.plPlease input the circle's radius: 100The area is: 31415.9265
File Handlingکار کردن با فایلها
را برای نگهداری file$ابتدا متغییر اسم فایل تعریف کنید.
)یا هر INFOتوسط دستگیره فایل openاسم دیگری( و دستور فایل فوق را باز کنید.
تمام فایل را داخل یک آرایه بریزید:@lines = <INFO ;>
( closeفایل را ببندید. )دستور ( printآرایه را چاپ کنید. )دستور
#!/usr/local/bin/perl
# basic09. pl COMP 519
# Program to open the password file,
# read it in, print it, and close it again.
$file = 'password.dat'; #Name the file
open(INFO, $file); #Open the file
@lines = <INFO>; #Read it into an array
close(INFO); #Close the file
print @lines; #Print the array
What happens if @lines is replaced by the scalar $lines?
کارهای دیگر با فایل:•open(INFO, $file); # Open for input, i.e. readingopen(INFO, ">$file"); # Open for new output, i.e. writingopen(INFO, ">>$file"); # Open for appendingopen(INFO, "<$file"); # also for reading
نوشتن در فایل:•print INFO "This line goes to the file.\n";
Example#!/usr/local/bin/perl
# basic09. pl COMP 519
# Program to open the password file,
# read it in, print it, and close it again.
$file = 'password.dat'; #Name the file
open(INFO, $file); #Open the file
@lines = <INFO>; #Read it into an array
close(INFO); #Close the file
print @lines; #Print the array
password.dat:
password1password2password3password4password5.........
bash-2.05b$ perl basic09.plpassword1password2password3password4password5.........
foreach-Statement
#!/usr/local/bin/perl# basic10.pl COMP519@food = ("apples", "pears", "eels");foreach $morsel (@food) # Visit each item in turn and call it # $morsel{print "$morsel \n"; # Print the itemprint "Yum yum\n"; # That was nice}
برای خواندن عناصر یک لیست به ترتیب به کار می foreachدستور •( C در زبان forرود. )مثل
bash-2.05b$ perl basic10.plapplesYum yumpearsYum yumeelsYum yum
Testing است.true هر رشته یا عدد غیر صفر معادل Perlدر
falseعدد صفر، کاراکتر صفر در یک رشته و رشته خالی معادل هستند.
در ادامه چند عبارت مقایسه ای روی اعداد و رشته ها نشان داده شده اند:
$a == $b # Is $a numerically equal to $b? #Beware: Don't use the = operator.
$a != $b # Is $a numerically unequal to $b?$a eq $b # Is $a string-equal to $b?$a ne $b # Is $a string-unequal to $b?
می توان از عملگرهای منطقی نیز استفاده کرد:
$(a && $b) #Is $a and $b true?$(a || $b) #Is either $a or $b true?
$(!a) #is $a false?
Control Operations
Loop Statements
Perl مثل Java و C درای -do و while و forحلقه
until.است
#!/usr/local/bin/perl# basic11.pl COMP519for ($i = 0; $i < 10; ++$i)# Start with $i = 1# Do it while $i < 10# Increment $i before repeating{print "iteration $i\n";}
#!/usr/local/bin/perl# basic12.pl COMP519print "Password?\n";# Ask for input$a = <STDIN>;# Get inputchomp $a; #Remove the newline at endwhile ($a ne "fred") #While input is wrong..{ print "sorry. Again?\n"; #Ask again $a = <STDIN>;# Get input again chomp $a;# Chop off newline again}
#!/usr/local/bin/perl# basic13.pl COMP519do{print "Password? "; #Ask for input$a = <STDIN>; #Get inputchomp $a; # Chop off newline}until($a eq "fred")# Redo until correct input
for
do-untilwhile
Examples
bash-2.05b$ perl basic11.pliteration 0iteration 1iteration 2iteration 3iteration 4iteration 5iteration 6iteration 7iteration 8iteration 9
for while
do-until
bash-2.05b$ perl basic12.plPassword?wewsorry. Again?wqqwsorry. Again?fred
bash-2.05b$ perl basic13.plPassword? werfwePassword? qfvccPassword? qcqcPassword? fred
Conditionals
if ($a){
print "The string is not empty\n;"}
else{
print "The string is empty\n;"}
•Perl دارای دستور if then else است.
وجود e یک elsifدقت کنید که در •if (!$a) # The ! is the not operatorندارد!
{ print "The string is empty\n";}elsif (length($a) == 1)# If above fails, try this{print "The string has one character\n";}elsif (length($a) == 2)# If that fails, try this{print "The string has two characters\n";}else #Now, everything has failed{print "The string has lots of characters\n";}
Regular Expressions
یک الگو است که با رشته داده شده (RE)عبارت منظم مطابقت دارد/ندارد.
RE قرار می گیرد. / در بین دو عالمتشروع می شود. به این =~ مطابقت بعد از دیدن عملگر
عملگر، عملگر انطباق گفته می شود.
RE .به بزرگی و کوچکی حروف حساس است
برای چک کردن عدم انطباق استفاده می شود. !~ عملگر
$sentence =~ /the/ gives TRUE if the appears in $sentence
if $sentence = "The quick brown fox"; then the above match will be FALSE.
$sentence !~ /the/ is TRUE because the string “the” does not appear in $sentence
Example
#!/usr/local/bin/perl# basic14.pl COMP519
$sentence = "The quick brown fox";$a = ($sentence =~ /the/) ; $b= ($sentence !~ /the/); print "Output gives $a and $b\n";
bash-2.05b$ perl basic14.pl
Output gives and 1
The $_ Special Variable
قرار $_ می توان ابتدا عبارت مورد نظر را در متغییر مخصوص داد. در این حالت نیازی به تایپ کردن عملگر انطباق نیست.
if ($sentence =~ /under/){print "We're talking about rugby\n";}
را در شرط استفاده نمود:REمی توان
اگر شرایط زیر برقرار باشد شرط درست است:
$sentence = "Up and under";$sentence = "Best in Sunderland";
if (/under/){print "We're talking about rugby\n";}
در زبان $_ تغییرنکته: Perl برای بسیاری از
عملگرها متغییر پیش فرض است و استفاده
زیادی دارد.
More on REs ها نیاز به خالقیت دارد.REایجاد
. # Any single character except a newline^ # The beginning of the line or string$ # The end of the line or string* # Zero or more of the last character+ # One or more of the last character? # Zero or one of the last character
t.e # t followed by anything followed by e. This will match tre, tle but not te, tale^f # f at the beginning of a line^ftp # ftp at the beginning of a linee$ # e at the end of a linetle$ # tle at the end of a lineund* # un followed by zero or more d characters. This will match un, und, undd, unddd,….* # Any string without a newline. This is because the . matches anything except # a newline and the * means zero or more of these.^$ # A line with nothing in it.
چند مثال:
محصور شود. // باید بین REبخاطر داشته باشید که هر
در اینجا بعضی از متغییرهای و معنی آنها REمخصوص در
آورده شده است.
Even more on REs
jelly|cream # Either jelly or cream
(eg|le)gs # Either eggs or legs
(da+) # Either da or dada or dadada or...
استفاده کرد که با تمام کاراکترهای داخل آن ][ می توان ازمطابقت دارد.
به معنای بین -•
notبه معنای ^ •
[qjk] # Either q or j or k[^qjk] # Neither q nor j nor k[a-z] # Anything from a to z inclusive[^a-z] # No lower case letters[a-zA-Z] # Any letter[a-z]+ # Any non-zero sequence of lower case letters
برای همگروه کردن اشیاء با هم استفاده کنید. )..(یا | از)به معنای یا(
Still More on REs
\n # A newline\t # A tab\w # Any alphanumeric (word) character.
# The same as [a-zA-Z0-9_]\W # Any non-word character.
# The same as [^a-zA-Z0-9_]\d # Any digit. The same as [0-9]\D # Any non-digit. The same as [^0-9]\s # Any whitespace character: space,
# tab, newline, etc\S # Any non-whitespace character\b # A word boundary, outside [] only\B # No word boundary
و معنی آنها:REتعدادی دیگر از متغییرهای مخصوص در
\| # Vertical bar\[ # An open square bracket\) # A closing parenthesis\* # An asterisk\^ # A carat symbol\/ # A slash\\ # A backslash
Some Example REs
[01] # Either "0" or "1"/\0 # A division by zero: "/0"
/\0 # A division by zero with a space: "/ 0"\/\s0 # A division by zero with a whitespace:
/" # 0 "where the space may be a tab etc.* /\0 # A division by zero with possibly some
# spaces: "/0" or "/ 0" or "/ 0" etc.\/\s*0 # A division by zero with possibly some whitespace.\/\s*0\.0* # As the previous one, but with decimal
# point and maybe some 0s after it. Accepts # /"0". and "/0.0" and "/0.00" etc and # /"0". and "/ 0.0" and "/ 0.00" etc.
محصور شود. // باید بین REبخاطر داشته باشید که هر
REبهترین راه این است که با تمرین و ممارست نحوه استفاده از را یاد بگیرید. در این جا چند مثال دیگر آورده شده است:
Substitution برای جایگزینی انطباقهای پیدا شده با یک رشته دیگر استفاده کرد. sمی توان از تابع
$sentence =~ s/london/London/; را با london اولین sentence$در رشته London .عوض می کند
London را با london اولین $_در رشته عوض می کند.
s/london/London/;
London را با ها london تمام $_در رشته (.gعوض می کند )با استفاده از گزینه
s/london/London/g;
RE زیر تمام حاالت کلمه london مثل lOndon, lonDON, LoNDoN را باLondon عوض می کند.
s/[Ll][Oo][Nn][Dd][Oo][Nn]/London/g
است که بزرگ و کوچک بودن حروف iاما یک راه حل ساده تر استفاده از گزینه را در نظر نمی گیرد.
.نیز استفاده کرد /.../ را می توان در انطباق iگزینه
s/london/London/gi
Example/!#usr/local/bin/perl #basic15.pl COMP519
" = _$I love london, but not london or LoNdoN;"$a = s/london/London/;
print "$a changes in $_ \n;"$a= s/london/London/g ;
print "$a changes in $_ \n;"$a= s/london/old London/gi;
print "$a changes in $_ \n;"
bash-2.05b$ perl basic15.pl1 changes in I love London, but not london or LoNdoN1 changes in I love London, but not London or LoNdoN3 changes in I love old London, but not old London or old London
اتفاق می افتند. $_ دقت کنید تغییرات در متغییرتعداد تغییرات را می شمارد. a$در حالیکه
Remembering Patterns برای فراخوانی 9,...,\1\ یعنی REمی توان از متغییرهای مخصوص کدهای
)با یا بدون جایگزینی( استفاده کرد.REانطباقهای پیدا شده در همان
$_ = "Lord Whopper of Fibbing";s/([A-Z])/:\1:/g;print "$_\n";
if (/(\b.+\b) \1/){print "Found $1 repeated\n";}
تمام حروف بزرگ را بین : محصور می کند. :L:ord :W:hopper of :F:ibbing.
را $_تمام کلمات تکراری داخل مشخص می کند.
در باقی کد نیز استفاده کرد. 9,...,$1$ حتی می توان از متغییرهای
برای پیدا کردن $' و $& و $`بعد از انطباق می توان از متغییرهای آنچه که قبل از انطباق، در حین انطباق و بعد از آن پیدا شده است؛
استفاده کرد.
$search = "the";s/${search}re/xxx/;
عوض xxx را با $_ های داخل there تمام می کند.
Some Future Needs
s/\+/ /g; s/%([0-9A-F][0-9A-F])/pack("c",hex($1))/ge;
s/\+/ /g را با یک فاصله جایگزین می کند. +تمام عالمتهای
[(%/0-9A-F[]0-9A-F/)] هایی را که بعد از آنها دو رقم هگزادسیمال وجود %تمام دارد را پیدا می کند.
استفاده شود.1$ را همگروه می کند تا بعدا توسط % کاراکترهای بعد از )(
hex($1) را تبدیل به یک رشته هگزادسیمال می کند. 1$هگزادسیمال داخل عدد
یک مقدار را می گیرد و آنرا بصورت یک ساختمان داده می آورد. )(packتابع
به تابع می گوید که رشته هگزادسیمال را تبدیل به معادل کاراکتری آن ”c"گزینه کند.
e .طرف راست را بعنوان یک عبارت ارزیابی می کند
Translationبرای ترجمه کاراکتر به کاراکتر استفاده می گردد. tr تابع
و d ها با bتمام ، e ها با a تمام sentence$در عوض می شوند. خروجی تابع تعداد f ها با cتمام
ترجمه های انجام شده است.
$sentence =~ tr/abc/edf/
معنایی ندارند.tr در تابع REاکثر کدهای مخصوص
$count = ($sentence =~ tr/*/*/);
میریزد. count$را می شمارد و در متغییر sentence$ های موجود در تمام *
tr/a-z/A-Z/; را بزرگ می کند. $_ تمام حروف
مثالهای زیر را در نظر بگیرید:
tr/\,\.//; را حذف می $_ تمام کاما ها و نقطه های کند.
Splitیک رشته را تکه تکه کرده و در یک آرایه می ریزد. split تابع
$info = "Caine:Michael:Actor:14, Leafy Drive";@personal = split(/:/, $info);
@personal = ("Caine", "Michael", "Actor", "14, Leafy Drive");
@personal = split(/:/); کار می کند.$_ روی متغییر
@personal = ("Capes", "Geoff", "Shot putter", "Big Avenue");
$_ = "Capes:Geoff::Shot putter:::Big Avenue";@personal = split(/:+/);
استفاده کرد. splitها داخل تابع RE می توان از
$_ = "Capes:Geoff::Shot putter:::Big Avenue";@personal = split(/:/);
@personal = ("Capes", "Geoff", "", "Shot putter", "", "", "Big Avenue");
کارکترهای یک کلمه
کلمات یک جمله
جمالت یک پاراگراف
@chars = split(//, $word);@words = split(/ /, $sentence);@sentences = split(/\./, $paragraph)
Some Future Needs
@parameter_list = split(/&/,$result); #split string on '&' characters
foreach (@parameter_list){ s/\+/ /g ; s/%([0-9A-F][0-9][A-F])/pack("c",hex($1))/ge; }
از هم جدا می کنیم. و & را براساس queryابتدا، ما •می ریزیم. parameter_list@نتیجه را در آرایه
$_سپس ما توی آرایه می چرخیم. هر آیتم آرایه داخل •قرار می گیرد و تغییرات روی آن انجام می شود.
Hashesهاشها آرایه ای هستند که در آنها هر عنصر دارای یک کلید
رشته ای است.
%ages = ("Michael Caine", 39, "Dirty Den", 34, "Angie", 27, "Willy", "21 in dog years", "The Queen Mother", 108);
$ages{"Michael Caine"}; # 39$ages{"Dirty Den"}; # 34$ages{"Angie"}; # 27$ages{"Willy"}; # "21 in dog years"$ages{"The Queen Mother"}; # 108
شده است. $تبدیل به یک % هر
می توان یک هاش را تبدیل به آرایه کرد و برعکس.
@info = %ages; # @info is a list array. It now has 10 elements$info[5]; # Returns the value 27 from the list array @info%moreages = @info; # %moreages is a hash. # It is the same as %ages
Operatorsمی توان به عناصر هاش را به طرق مختلف دسترسی داشت.
foreach $person (keys %ages){print "I know the age of $person\n";}foreach $age (values %ages){print "Somebody is $age\n";}
Keys لیستی از کلید ها را بر میگرداند.
Values لیستی از مقدارها را بر می
.گرداند.
while (($person, $age) = each(%ages)){print "$person is $age\n";}
each یک زوجkey/value را بر می گرداند.
if (exists $ages{"The Queen Mother"}){print "She is still alive…\n";}
درداخل هاش بصورت value اگر مقدارمقدار exist تابع کلید موجود باشد
درست را بر می گرداند.
delete $ages{"The Queen Mother"};delete کلید مورد نظر را به همراه
مقدارش را حذف می کند.
Subroutines یک سابروتین را تعریف نمود. subمی توان توسط
sub mysubroutine{print "Not a very interesting routine\n";print "This does the same thing every time\n";}
نیازی به تعیین لیست پارامتر ها نیست
به همراه اسم آن استفاده کنید.&برای صدا زدن یک سابروتین از
&mysubroutine; # Call the subroutine&mysubroutine($_); # Call it with a parameter&mysubroutine(1+2, $_); # Call it with two parameters
Parametersبه سابروتین فرستاده می شود. می @_ لیست پارامترها از طریق آرایه
و ... به پارامترها دسترسی داشت. [1$_] و [0$_] توان از طریق
ندارند. $_این متغییرها هیچ ربطی به متغییر عمومی
sub printargs{print "@_\n";}
&printargs("perly", "king"); # Example prints "perly king"&printargs("frog", "and", "toad"); # Prints "frog and toad"
sub printfirsttwo{print "Your first argument was $_[0]\n";print "and $_[1] was your second\n";}
Returning Values برای بارگرداندن خروجی استفاده نمود.returnمی توان از کلمه کلیدی
استفاده نکنیم آخرین انتساب به عنوان خروجی برگردانده returnاگر از می شود.
sub maximum{ if ($_[0] > $_[1]) { return $_[0]; } else { return $_[1]; }}
$biggest = &maximum(37, 24);
# Now $biggest is 37
Local Variablesمحلی هستند.[,2[,$_]1[,$_]0$_] و متغییرهای @_ آرایه
به صورت پیش فرض عمومی هستند اما می Perlمتغببرهای توان متغییر محلی نیز تعریف نمود.
sub inside{my ($a, $b); # Make local variables using the # “my” keyword($a, $b) = ($_[0], $_[1]); # Assign values$a =~ s/ //g; # Strip spaces from$b =~ s/ //g; # local variables($a =~ /$b/ || $b =~ /$a/); # Is $b inside $a or $a inside $b?}
&inside("lemon", "dole money"); # true
More on Parameters
sub maximum{ # returns the maximum of the # parameters passed to function my ($current_max) = shift @_; foreach (@_) { if ($_ > $current_max) { $current_max = $_; } } $current_max; # return the max}
SortingPerl دارای تابع sort:برای مرتب کردن عناصر یک لیست است
این تابع اعداد را بصورت کاراکتری مرتب می کند. برای مرتب کردن اعداد بصورت ریاضی از کد زیر استفاده کنید:
اعالم کرده ایم.sortدقت کنید که نحوه مقایسه را به تابع می توان عناصر لیست را بصورت معکوس نیز مرتب کرد.
@names = (“Joe”, “Bob”, “Bill”, “Mark”);
@sorted = sort @names; # @sorted now has the list # (“Bill”, “Bob”, “Joe”, ”Mark”)
@numbers = (12, 3, 1, 8, 20);
@sorted = sort { $a <=> $b } @numbers; # @sorted now has the list # (1, 3, 8, 12, 20)
@numbers = (12, 3, 1, 8, 20);@sorted = reverse sort { $a <=> $b } @numbers; # sort the list from biggest # to smallest
References
$age=42;
$ref_age =\$age;
@stooges = ("Curly","Larry","Moe");
$ref_stooges = \@stooges;
$ref_salaries = [42500,29800,50000,35250];
$ref_ages ={
‘Curly’ => 41,
‘Larry’ => 48,
‘Moe’ => 43,
};
برای ارجاع:
برای ][برای متغییرها از \ از برای هاشها }{آرایه ها و از استفاده کنید.
$$ref_age = 30;
$$ref_stooges[3] = "Maxine“;
$ref_stooges -> [3] = "Maxine“;
برای $$برای از بین بردن اثر ارجاع از برای لیستها استفاده -<متفیرها و از
کنید.