。。。
- #!/usr/bin/perl
-
-
my @names = qw /fred barney betty dino Wilma pebbles/;
-
my $result = &which_element_is("dino", @names);
-
-
print "index is $result\n";
-
-
sub which_element_is{
-
my($what, @array) = @_;
-
foreach(0 .. $#array){
-
if($what eq $array[$_]){
-
return $_;
-
}
-
}
-
-1;
-
}
组@array(第一个索引值为0,
最后一个为$#array非标量返回值
sub list_from_fred_to_barney{
$a = shift;
$b = shift;
if($a < $b){
$a .. $b;
}else{
reverse $b .. $a;
}
}
@c = &list_from_fred_to_barney(10,4);
print "@c\n";
Since all Perl subroutines can be called in a way that needs a return value, it’d be a bit
wasteful to have to declare special syntax to “return” a particular value for the majority
of the cases. So Larry made it simple. As Perl is chugging along in a subroutine, it is
calculating values as part of its series of actions.
Whatever calculation is last performed in a subroutine is automatically also the return value.- sub func{
-
1 + 2;
-
}
-
-
print func;
-
-
we get 3;
- sub func{
-
1 + 2;
-
if (2 < 1){
-
1;
-
}else{
-
3;}
-
}
-
-
print func;
- get 3.
- sub sum_of_fred_and_barney {
-
print "Hey, you called the sum_of_fred_and_barney subroutine!\n";
-
$fred + $barney; # That's not really the return value!
-
print "Hey, I'm returning a value now!\n
In this example, the last expression evaluated is not the addition; it’s the print state-
ment.
Its return value will normally be 1, meaning “printing was successful,”* but that’s
not the return value you actually wanted. So be careful when adding additional code
to a subroutine, since the last expression evaluated will be the return value.
So, what happened to the sum of $fred and $barney in that second (faulty) subroutine?
We didn’t put it anywhere, so Perl discarded it. If you had requested warnings, Perl
(noticing that there’s nothing useful about adding two variables and discarding the
result) would likely warn you about something like “a useless use of addition in a void context.” The term void context is just a fancy way of saying that the answer isn’t being
stored in a variable or used in any other way.
- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;
-
my $r = &find_index("barney", @names);
-
print $r;
-
sub find_index{
-
my ($des, @array) = @_;
-
-
foreach (0..$#array){
-
if ($array[$_] eq $des){
-
return $_;
-
}
-
}
-
-1;
-
}
- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my @fred = qw{ 1 3 5 7 9 };
-
my $fred_total = total(@fred);
-
print "The total of \@fred is $fred_total.\n";
-
print "Enter some numbers on separate lines: ";
-
my $user_total = total(<STDIN>);
-
print "The total of those numbers is $user_total.\n";
-
-
-
-
sub total{
-
my $sum;
-
-
foreach (@_){
-
$sum += $_;
-
}
-
$sum;
-
}
阅读(353) | 评论(0) | 转发(0) |