Revision / Summary of lists - Perl
Archive - Originally posted on "The Horse's Mouth" - 2009-06-10 09:54:33 - Graham EllisWe've started the third day of this week's Perl course with a revision of some features of lists ... posting here as there are some useful reminders (and I came back later to add more comments!)
# Revision / Summary of lists - Perl
$abc = 16; # single value
@abc = (16,14,12,11,10,8,7,2); # multiple values - a list
print "Single value is $abc\n";
print "Single value from \@abc $abc[2] (third element)\n";
print "Whole list \@abc: @abc \n";
# ------ Processing lists as a whole via functions;
# ------ grep to FILTER
# ------ map to transform every element
print "process whole list ...";
# Regulr expression - a 1 follwed by another character NOT a 0 1 or 2
@teens = grep(/^1[^012]/,@abc);
print "Teenagers are @teens\n";
@nextyear = map($_+1,@abc); # Add 1 to each element
push @nextyear,1;
print "Next year ages will be @nextyear\n";
# ------ $#listname tells us top index number
print "You now have ",$#abc," Children\n";
# -------- Handling each element of a list
# ---- use "for" if I need to know the key no.
# ---- use "foreach" if I just want to process content
for ($k=0; $k<=$#nextyear; $k++) { # Start ; end condition; step syntax
print "Child $k will be $nextyear[$k] next year\n";
}
foreach $kiddo (@nextyear) {
print "We will have a $kiddo y.o. child\n";
}
We run public Perl Programming courses 4 to 6 times a year, and various advanced Perl courses regularly but a little less often - see here for details.