Subroutine Parameters
Monday, September 22nd, 2008Subroutine 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
{
return $arg1 + $arg2;
}
echo get_sum(3);
python
return arg1 + arg2;
print get_sum(3);
ruby
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
{
return count(func_get_args());
}
echo get_length(1, 2, 3);
python
return len(args);
print get_length(1, 2, 3);
ruby
return args.length;
end
puts get_length(1, 2, 3)
perl
{
return scalar(@_);
}
print get_length(1, 2, 3);
bash
{
return ${#*};
}
get_length 1 2 3 || echo $?
javascript
function get_length()
{
return arguments.length
}
document.write(get_length(1, 2, 3));
</script>
java
Create a file: Test.java
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
return arg2*arg2;
print get_sum(arg2 = 3, arg1 = 1); // 9