文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>2 tricks in perl programming

2 tricks in perl programming

时间:2006-10-17  来源:megazeng

Here i want to list some tricks while learning perl, they are listed as follows:

A. You can find in many perl books say ”If you are a C developer or Java developer, you will definitely think that a function or method should add "return" keyword if the fuction or method is required to return values, But in perl, actually, it is not required.“ Let's see the example 1 below:

#!/usr/bin/perl -w
        my @param = (1..10);
        $result = &sum(@param);
        print $result;  # 55 will be printed out

        sub sum{
                 my $sum =shift @_;
                foreach (0..$#_){

                        $sum+=$_[$_];
                }

               $sum;
        }


All right, return is not used and 55 is printed out. But let's see another example 2:

#!/usr/bin/perl -w


    @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;
    my $result = &which_element_is("dino", @names);
    print $result;
    sub which_element_is {
      my($what, @array) = @_;
      foreach (0..$#array) { # indices of @array's elements

        if ($what eq $array[$_]) {
            $array[$_]; # will return if mactched, right ???

        }
      }
      -1; # also without "return"
    }


Guess will the above code work ???

......

ACTUALLY, the value in the if block will never return if we do not provide the key word "return". Is it interesting ???

B. As we know that if we want to call a sub routine , we will need to use "&" before the name of the sub routine. But if the sub rountine is defined before the code which calls this sub rountine, "&" can be omitted. See the below example 3:

#/usr/bin/perl -w

    sub division {
      $_[0] / $_[1]; # Divide first param by second
    }
    my $quotient = division 355, 113;


But you should pay attention on the sub routine name, if the name is the same as the perl built in sub routine name, the sub rountine you defined will never been called. see example 4 below :

#/usr/bin/perl -w

sub chomp {
      print "Munch, munch!\n";
    }

    &chomp; # this sub routine is not what you defined


Cool ??? :)
相关阅读 更多 +
排行榜 更多 +
瓢虫少女

瓢虫少女

飞行射击 下载
潜艇鱼雷

潜艇鱼雷

飞行射击 下载
网络掠夺者

网络掠夺者

飞行射击 下载