Changing the Elements of an Array
So we have @names . We want to change it. Run
this:
print "Enter a name :";
chomp ($x=<STDIN>);
@names=("Muriel","Gavin","Susanne","Sarah");
print "@names\n";
push (@names, $x);
print "@names\n";
Fairly self explanatory. The push function just adds a value on to the end of the array.
Of course, Perl being Perl, it doesn't have to be just the one value:
print "Enter a name :";
chop ($x=<STDIN>);
@names=("Muriel","Gavin","Susanne","Sarah");
@cities=("Brussels","Hamburg","London","Breda");
print "@names\n";
push (@names, $x, 10, @cities[2..4]);
print "@names\n";
This is worth looking at in more detail. It appears there is no fifth element of
@cities , as referred to by @cities[2..4] .
Actually, there is a fifth element. Add this to the end of the example :
print "There are ",scalar(@names)," elements in \@names\n";
There appear to be 8 elements in @names . However, we have just proved there are in fact 9.
The reason there are 9 is that we referred to non-existent elements of @cities , and Perl
has quite happily extended @names to suit. The array @cities remains unchanged. Try poping
the array if you don't believe me.
So that's push . Now for some...