Google

Lesson one part 2

Lesson one part 2

Contact:[email protected]

What about a loop?

#!/usr/bin/perl

$maximum = 10;
$number = 1;
while ( $number <= $maximum ) {
  print "$number\n";
  $number++;
}

Here we are setting $maximum and $number and saying "while the number is
less than or equal to the maximum, run everything between the { and the }."
We increment $number with the perl-ism "++" or, in other words, add one to
$number. The opposite of that would be "� " meaning subtract one from the
variable.

We can also construct arrays (lists) of items and pick things from them.

#!/usr/bin/perl

@days = ( "Sunday," "Monday," "Tuesday," "Wednesday," "Thursday," "Friday."
"Saturday" );

$total_days = @days;
print "There are $total_days days in the week.\n";
print "The first day of the week is @days[0].\n";
print "The last day of the week is @days[$total_days - 1].\n";

@time = localtime(time);
print "Today is @days[@time[6]].\n";

What's that, class? You're confused? Let me explain. A few things are
happening here. First, we are making an array called @days with all the days
of the week in it. We can call any particular day by referencing it by
number, but arrays are numbered starting from 0, so @days[1] is "Monday."

@days is an array, but when we call it like a variable ($total_days =
@days), it returns the total number of elements in that array. In this case,
that would be 7. But don't forget that the last element of the array @days
is 6, not 7, because the array is numbered from 0. So, in order to get the
last element of the array, we call it like this: @days[$total_ days � 1].

Next we are using a handy Perl function called localtime which returns an
array representing the current date and time. It just so happens that array
element 6 is the day of the week on a 0 � 6 scale, so we can convert that to
the long form by calling the @time[6]'th element of the @days array:
@days[@time[6]].

Tip: The function localtime exposes a number of items which are covered in
the manual page. In short, you can use them like this:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
To read up on localtime and many other functions, type:
perldoc perlfunc


Back to the Index