Learning Perl chapter 4 練習題

來源:互聯網
上載者:User

原文發表在網易部落格 2010-11-06 13:07:36

第1題和第2題

#!perl -w
#chapter 4 , exercise one and two
use strict;
sub total{
    my $sum;
    foreach $_ (@_){
        $sum += $_;
        }
        $sum;
    }
my @fred=(1,3,5,7,9);
print "sum of (@fred) is:\t ",&total(@fred),"\n";

print "sum of 1 to 100 is :\t",&total(1..100),"\n";

第3題

#!perl -w
#chapter 4 , exercise 3
use strict;
sub getSum{
    my $sum=0;
    foreach $_ (@_){
        $sum+=$_;
        }
    $sum;
    }
sub getAverage{
    my @abovelist=();
    my $length=@_;
    my $average=-1;
    $average=&getSum(@_)/$length;
    }
sub above_average{
    my @abovelist;
    my $average=&getAverage(@_);
    foreach $_ (@_){
        if($_ > $average){
            push @abovelist, $_
            }
        }
    return @abovelist;
    }
my @fred=&above_average(1..10);
print "above the average in one to ten is :(@fred)\n";

 

第4題

#!perl -w
use strict;
use 5.010;
sub greet1{
    state $lastPerson="";
    if(@_ ==1 ){
        if($lastPerson ne ""){
            print "Hi,$_[0]!$lastPerson is also here.\n";
            }else{
                print "Hi,$_[0]!You are the first one here!\n";
                }
        $lastPerson=$_[0];
        }
    }
&greet1("leipei");
&greet1("ada");

 

第5題

#!perl -w
use strict;
use 5.010;
sub greet2{
    state @personlist;
    if(@_ == 1){
        if(@personlist >0){
            print "Hi,$_[0]! I have seen:@personlist\n";
            }else{
                print "Hi,$_[0]! You are the firt one here.\n";
                }
        push (@personlist,$_[0]);
        }
    }
greet2("Fred");
greet2("Barney");
greet2("Wilma");
greet2("Betty");

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.