Archive for the ‘程序语言系列’ Category

Subroutine Parameters

Monday, September 22nd, 2008

Subroutine Parameters has these most important property:

1. default parameters

If some parameters is not be given, would have a default value for these parameters. In Python, the parameters have default value must after the must-given parameters. Php, Python, Ruby have this property.

php

function get_sum($arg1, $arg2 = 2)
{
    return $arg1 + $arg2;
}

echo get_sum(3);

python

def get_sum(arg1, arg2 = 2):
    return arg1 + arg2;

print get_sum(3);

ruby

def get_sum(arg1, arg2 = 2)
    return arg1 + arg2;
end

puts get_sum(3);

2. variable-length parameter lists

A special way to get all the parameters, even the arguments are not given. Php, Python, Ruby, Perl, Bash, Javascript, Java have this property.

php

function get_length()
{
    return count(func_get_args());
}

echo get_length(1, 2, 3);

python

def get_length(*args):
    return len(args);

print get_length(1, 2, 3);

ruby

def get_length(*args)
    return args.length;
end

puts get_length(1, 2, 3)

perl

sub get_length
{
    return scalar(@_);
}

print get_length(1, 2, 3);

bash

function get_length()
{
    return ${#*};
}

get_length 1 2 3 || echo $?

javascript

<script type="text/javascript">
function get_length()
{
    return arguments.length
}

document.write(get_length(1, 2, 3));
</script>

java
Create a file: Test.java

public class Test{
    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.get_length(1, 2, 3));
    }
    
    public int get_length(int... args)
    {
        return args.length;
    }
}

3. named parameters

You can change the order of the arguments or just give some of the arguments with this property, Python have this property.

python

def get_sum(arg1 = 1, arg2):
    return arg2*arg2;

print get_sum(arg2 = 3, arg1 = 1); // 9

Subroutine Standard

Monday, September 22nd, 2008

Here document

Sunday, August 24th, 2008

Exception

Monday, August 18th, 2008

Constructor & Destructor

Sunday, August 10th, 2008