Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 4

Perl

http://www.perl.com

Factorial (1) Michael Neumann


sub fac {
my ($n) = @_;
if ($n < 2) {
return $n;
}
else {
return $n * fac($n-1);
}
}
print fac(6), "\n";

Calculates the factorial. Results 720.

Factorial (2) Arnaud ASSAD


#!/usr/bin/perl
sub fac {
$_[0]>1?$_[0]*fac($_[0]-1):1;
}
print fac(6);

Calculates the factorial. Results 720.

Hello World Michael Neumann


# Hello World in Perl
print "Hello World\n";

Prints "Hello World" onto the screen.

References Michael Neumann

# array -> reference


@arr
= (1, 2, 3);
$arr_ref = \@arr;
# reference -> array
$arr_ref2 = [1, 2, 3];
@arr2
= @$arr_ref2;
# array access
$item
= $arr[0];
$item
= $arr_ref->[0];

References and Arrays; Array access

Squares (1) Michael Neumann


for($i = 1; $i <= 10; ++$i) {
print $i*$i, ' ';
}

Outputs the squares from 1 to 10.

Squares (2) Michael Neumann


@squares = ();
foreach my $i (1..10) {
push(@squares, $i * $i);
}
print join(" ", @squares), "\n";

Outputs the squares from 1 to 10.

Squares (3) Pixel


print join(" ", map { $_ ** 2 } 1..10), "\n";

Outputs the squares from 1 to 10.

Squares (4) Arnaud ASSAD


for (1..10) { print $_**2," "};print$/;

Outputs the squares from 1 to 10.

Substitution Michael Neumann


$a = 3;
$b = 5;
$c = $a + $b;
print "$a + $b = $c";

Prints 3 + 5 = 8 onto the screen.

Tcl;;;;;;;;;;;;;;;;;;;;;;

Tcl

Hello World Michael Neumann


puts "Hello World"

Prints "Hello World" onto the screen.

Squares Michael Neumann


set i 1
while {$i <= 10} {puts [expr $i*$i];set i [expr $i+1]}

Outputs the squares from 1 to 10.

Substitution Michael Neumann


set a 3
set b 5
puts "$a + $b = [expr $a + $b]"

Prints 3 + 5 = 8 onto the screen.

Hello World Tcl/Tk Michael Neumann


button .hello -text "Hello World" -command {destroy .}
pack .hello

Prints "Hello World" onto the screen.

You might also like