Perl Programming Page 3 - Perl: Sailing the List(less) Seas |
A slice is a range of elements in a list. If it is only one element in a list, then it is known as a scalar slice and you refer to it with the $ symbol. If the slice has more than one element you use the @ symbol, because technically, a multi-element slice is itself a list. Let's take another look at our list of gladiator names. Of those names, I would like to specify that one is the champion. I am going to create a new variable named $champion and assign it the value of the champion's name. Here it is in code: #!/usr/bin/perl @gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker '); $champion=$gladiators[2]; print $champion; Here we have stored the name of our champion in the variable. When we print it out we get the following result: CountFistula Now what if we had some tag team champions and wanted to add them to a new list? Remember that there are two values now, and it is no longer a scalar, so you switch back to the @ symbol: #!/usr/bin/perl @gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker '); @tagchamps=@gladiators[2,3]; print @tagchamps; This will print out: CountFistula TheNutcracker Just for kicks, go ahead and try this code (I replaced the @ symbols with $ symbols): #!/usr/bin/perl @gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker '); $tagchamps=$gladiators[2,3]; print $tagchamps; This will print out: The NutCracker Perl only takes one of the values, as it sees the $ symbol and is only expecting a scalar and not a list. Printing the Number of Elements in a List This method is pretty simple, and hardly requires its own section, with a pristine heading and all, but what the heck. If you want to know how many elements are in a list, you can do so in the following manner (just remember to add one to the result, as the result is just the number of the last element in the array, and not really the full length of the array): #!/usr/bin/perl @gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker '); print $#gladiators; Here we have the result: 3 Remember: element indexes begin with 0, so we add one to the number for our true number of elements. Although really, we could just use the following code and not worry about remembering a thing at all: #!/usr/bin/perl @gladiators=('Nitro ', 'Blaze ', 'CountFistula ','TheNutcracker '); print $#gladiators+1; Giving us: 4
blog comments powered by Disqus |
|
|
|
|
|
|
|