[Courses] [Perl] Part 2: Scalar Variables

Karine Delvare kproot at nerim.net
Sun Apr 10 04:18:22 EST 2005


Hello Dan, thanks for the Perl course!

Below is my homework, please tell me if I'm sending this too early.

> 5) Exercises
> 
> a) Write a program called 'average.pl' to calculate the average of
> the following numbers: 23, 28, 31, 17, 1

#!/usr/bin/perl -w

use strict;

my $num1 = 23;
my $num2 = 28;
my $num3 = 31;
my $num4 = 17;
my $num5 = 1;

my $total = $num1 + $num2 + $num3 + $num4 + $num5;

my $average = $total / 5;

print "Average: $average\n";

> b) Consider the following program:
> 
>    #!/usr/bin/perl -w
>    use strict;
> 
>    my $foo = 'Suzy' x 4;
>    print "$foo\n";
> 
> What does the "x" operator do? Why can't we write "4 x 'Suzy'" as
> well as "'Suzy' x 4"?

Considering that the program output was SuzySuzySuzySuzy, the "x" operator seems to concatenate a string with itself, as many times as asked for (don't know if there is a proper english term for that, but that operator is cool!)

I tried to think a bit about 4 x 'Suzy'. Perl has to know which is the string and which is the "multiplicator". In that example it could guess it, but what about 4 x 3? 4 x 3 outputs "444", but 3 x 4 outputs "3333". So operands need to be ordered.

> c) Consider the following program:
> 
>    #!/usr/bin/perl -w
>    use strict;
> 
>    my $a = q/This is string A/;   # using slash
>    my $b = q!This is string B!;   # using exclamation point
>    my $c = q:This is string C:;   # using colon
>    print "$a\n$b\n$c\n";
> 
> What does the "q" operator do? What is the advantage of using it
> rather than a single quote?

Another cool operator! The output was:
This is string A
This is string B
This is string C
So it allows to replace the quote delimiters with any character. It can be an advantage if the string to quote containes quotes and/or double-quotes (makes me think about the way you can change the regular expressions delimiters, but I'm pretty sure we will encounter these later!)

Karine


More information about the Courses mailing list