| |||||||||||
| |||||||||||
References and variables in Perl - a summary Posted by admin (Graham Ellis), 14 February 2004 You may find this "revision table" useful if you've got a complex looking series of {}s, @s %s and $s in a piece of code you've been given to maintain!1. Perl variables are dynamically created as your program runs. $abc a scalar - holds a single number, string or reference @abc a list - holds a collection of scalars indexed by position number %abc a hash - holds a collection of scalars indexed by an scalar key of programmer's choice abc a file handle - used for a set of buffers / interface to file system &abc code - holds a named block of code - i.e. a sub *abc a typeglob - a scalar, a hash, a list, a code and a file handle all of the same name 2. If you're referrring to an individual scalar member of a collection, you use the $ prefix and you use square bracket subscript to indicate a member of a list curly brace subscript to indicate a member of a hash 3. If you preceed a variable name, you can reference and dereference. Thus: \ means "A reference to" or "the address of" if you prefer $ means "contents of" or "refers to" -> an alternative notation for $ example - $$abc[3] and $abc->[3] mean the same thing 4. You can create anonymous lists and hashes $abc = {"England", "London", "Wales","Cardiff"} creates an anonymous hash with two pairs $abc = {England => "London", Wales => "Cardiff"} alternative notation $abc = ["England", "London", "Wales","Cardiff"] creates an anonymous list with 4 members $abc = ("England", "London", "Wales","Cardiff") probably WRONG - $abc takes the value "4". 5. If you refer to a list in a scalar context, you'll get the number of elements in the list. If you refer to $#listname, you'll get the index number of the last element in the list. 6. You can also use {} to delimit a variable name - thus "$abkgs" means a string containing the contents of the variable $abkgs "${ab}kgs" means a string containing the contents of the variable $ab followed by "kgs" 7. You are limited only by your own ingenuity as to how complex a structure / expression you can make up using the above; I suggest that you use an Object Oriented design is you're looking at a really complex problem as this helps divide the code and complexity down into a series of different parts each of which can be developed and tested before you move on to the next stage. Posted by admin (Graham Ellis), 14 February 2004 Here's some sample (demo) code using most of the things I described in the previous post - can you work them out??Code:
This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |