zoukankan      html  css  js  c++  java
  • perl学习(1)子函数

    以下函数计算某年份是否为闰年

    #!/usr/bin/perl

    $my_year = 2000;
    if ( is_leap_year( $my_year ) )
    { # Call function with an argument
    print "$my_year is a leap year\n";
    }
    else
    {
    print "$my_year is not a leap year";
    }
    sub is_leap_year { # Function definition
    my $year = shift(@_); # Shift off the year from
    # the parameter list, @_
    return ((($year % 4 == 0) &;& ($year % 100 != 0)) ||
    ($year % 400 == 0)) ? 1 : 0; # What is returned from the function
    }

    上例中my $year = 2000;
     
    此代码中有一个关键字shift,给出相关解释。
     

    在阅读别人别人的perll代码的时候经常发现在头部都是 ”
    $变量=shift;”

    首先我们查下看下perldoc中对于shift()的解释

    perldoc -f shift
    
    shift ARRAY shift Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the "eval STRING", "BEGIN {}", "INIT {}", "CHECK {}", "UNITCHECK {}" and "END {}" constructs. See also "unshift", "push", and "pop". "shift" and "unshift" do the same thing to the left end of an array that "pop" and "push" do to the right end.

    shift off(可以理解为移除)数组中第一个变量并返回

    perl中默认如果不指明参数那么就根据上下文获取默认参数

    所以当我们定义这样一个pl文件

    1.pl
    
    $host = shift;

    那么显然shift操作的参数为@_ 也就是 @ARGV

    这句实现了直接获取用户传递的第一个参数。
    总之就是shift没有数组作为参数时,就是移动@_这个默认的参数。
    perl里经常用这种缺省方法的。

     


  • 相关阅读:
    java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä'...解决
    Dos命令查看端口占用及关闭教程
    IDEA中Tomcat启动出现乱码
    ORA-12514:TNS:监听程序当前无法识别连接描述符中请求的服务
    MySQL 面试问题分析总结
    深入Cpython (编写一个Cpython 模块)
    使用docker构建简约高效的镜像
    深入理解C
    ELK 起航
    jquery
  • 原文地址:https://www.cnblogs.com/luhouxiang/p/2176157.html
Copyright © 2011-2022 走看看