【Perl讀書筆記】基本數組,初始化

讀 《C程序員精通Perl》http://book.douban.com/subject/1232075/   3.1節 筆記



#!/usr/bin/perl

use strict;
use warnings;

my @array = (10, 20, 30, 3, 38, 7, 80);
my $biggest;
my $smallest;

$biggest = $array[0];
$smallest = $array[0];

print "number of array = $#array\n";

for (my $index=1; $index <= $#array; $index++) {

        print "array[$index] = $array[$index]\n";

        if ($array[$index] > $biggest) {

                $biggest = $array[$index];
        }   


        if ($array[$index] < $smallest) {

                $smallest = $array[$index];
        }   
}

print "smallest = $smallest, biggest = $biggest\n";

運行結果:

[root@localhost perl_practice]# ./array.pl
number of array = 6
array[1] = 20
array[2] = 30
array[3] = 3
array[4] = 38
array[5] = 7
array[6] = 80
smallest = 3, biggest = 80
[root@localhost perl_practice]#


初始化方式1:

#!/usr/bin/perl

use strict;
use warnings;

my $biggest = 2;
my $smallest = 100;
my @array_sub = ($biggest, $smallest);
my @array = ($biggest, $smallest, @array_sub);


print "number of array = $#array\n";

for (my $index=0; $index <= $#array; $index++) {

        print "array[$index] = $array[$index]\n";

}

print "array_sub are: @array_sub\n";
print "array are: @array\n";

運行結果:

[root@localhost perl_practice]# ./array1.pl   

number of array = 3

array[0] = 2

array[1] = 100

array[2] = 2

array[3] = 100

array_sub are: 2 100

array are: 2 100 2 100

[root@localhost perl_practice]#


初始化2:

#!/usr/bin/perl

use strict;
use warnings;

my @array = (1);

$array[5] = "hello";

print "number of array = $#array\n";

for (my $index=0; $index <= $#array; $index++) {

        print "array[$index] = $array[$index]\n";

}

#print "array are: @array\n";


運行結果:

[root@localhost perl_practice]# ./array2.pl
number of array = 5
array[0] = 1
Use of uninitialized value in concatenation (.) or string at ./array2.pl line 14.
array[1] =
Use of uninitialized value in concatenation (.) or string at ./array2.pl line 14.
array[2] =
Use of uninitialized value in concatenation (.) or string at ./array2.pl line 14.
array[3] =
Use of uninitialized value in concatenation (.) or string at ./array2.pl line 14.
array[4] =
array[5] = hello
[root@localhost perl_practice]#

初始化3:

#!/usr/bin/perl

use strict;
use warnings;

my @array = qw(hello calf_man 99);


print "number of array = $#array\n";

for (my $index=0; $index <= $#array; $index++) {

        print "array[$index] = $array[$index]\n";

}

print "array are: @array\n";

運行結果:

[root@localhost perl_practice]# ./array3.pl
number of array = 2
array[0] = hello
array[1] = calf_man
array[2] = 99
array are: hello calf_man 99
[root@localhost perl_practice]#











發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章