Perl: Sailing the List(less) Seas - Printing Specific Elements (
Page 2 of 4 )
Here is how we print only particular items from a list:
#!/usr/bin/perl
@gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker ');
print "These gladiators will mess you up: \n\n";
print @gladiators;
print "\n\n";
print "My favorite gladiator is ";
print $gladiators[2];
print "\n\n";
print "My most feared gladiator is ";
print $gladiators[3];
This gives us the result:
These gladiators will mess you up:
Nitro Blaze CountFistula TheNutcracker
My favorite gladiator is CountFistula
My most feared gladiator is TheNutcracker
Each element in a list has an index number, starting with zero. In this instance, 'Nitro' is at index 0 and 'TheNutcracker' is at index 3. There are four elements in total within the array.
Another way we can print individual elements in an array is like this:
#!/usr/bin/perl
@gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker ');
print "I made up these two gladiators: ";
print $gladiators[2] . "\t" . $gladiators[3];
Giving us:
I made up these two gladiators: CountFistula TheNutcracker
You may have noticed that when I wanted to print single elements from the list I switched back to the $ symbol. This is because individually, the items in the list are scalar variables. All of the elements in a list combined and separated by a comma are known as literals. That's just a little reference material for you; it always helps to know the lingo.
I know this may be a little confusing at the moment, but maybe this next section will clear the scalar/literal thing up a bit.