Perl

From Torben's Wiki
Jump to: navigation, search


Contents

Basics

rounding:

$T1 = sprintf("%.1f", $T1);

Multidim Lists / References

Creation

$scalarref = \$foo; 
$arrayref = \@ARGV; 
$hashref = \%ENV; 
$coderef = \&handler; 
$globref = \*foo; 

anonymous list: [ ... ]

$arrayref = [1, 2, 'a', 'b', 'c']; 
# $arrayref -> [2] == 'a' 
$arrayref = [1, 2, ['a', 'b', 'c']]; 
# $arrayref -> [2][1] == 'b' 

anonymous hash: { ... }

$hashref = { 
'Adam'  => 'Eve', 
'Clyde' => 'Bonnie', 
}; 

Save an array inside a hash:

$hash{$keyx} = \@list; 

Readout

@list = @{$hash{$keyx}}; 
# General: 
$str = ${$scalarref}; 
@lst = @{$arrayref}; 
%hash = %{$hashref}; 

perlref.html

Transpose Matrix

my @rows = ();
my @transposed = (); 

# This is each row in your table
push(@rows, [qw(0 1 2 3 4 5 6 7 8 9 10)]);
push(@rows, [qw(6 7 3 6 9 3 1 5 2 4 6)]);

for my $row (@rows) {
  for my $column (0 .. $#{$row}) {
    push(@{$transposed[$column]}, $row->[$column]);
  }
}

[1]

Web Access

use LWP::Simple; # network access
# read a file
my $content = get($url);
# download a file
getstore($url, $localfilename);

ANSIColor: Colorful Terminal Output

ANSIColor

use Term::ANSIColor;
print color 'bold blue';
print "This text is bold blue.\n";
print color 'reset';

Encoding

use Encode;
$oldencoding = 'ISO-8859-1'; # DOS: 'CP850';
$newencoding = 'utf8';
$str = decode($oldencoding,$str);
$str = encode($newencoding,$str);

File-Access

Recursive Delete of Folders / Deltree

use File::Path;
rmtree $outdir or die $!;

Copy

use File::Copy;
copy($source, $target);

Filesize

my $filesize = -s "test.txt";
Personal tools