Perl

Notes.

I love Perl

:-)

Must Know

downloadwrap
# hashes
my %hash = ( foo => 1, bar => 2 );
my $fooVal = $hash{foo};
my $hashRef = \%hash;
my $fooVal = $hashRef->{foo};
my @hkeys = keys %hash; # ('foo', 'bar')
my $ahash = { foo => 1, bar => 2 );
my $fooVal = $ahash->{foo};
my @hkeys = keys %{$ahash}; # ('foo', 'bar')

# arrays
my @array = ( 1, 2, 3..5 );
my $firstVal = $array[0];
my $numVals = $#array + 1; # or: scalar @array
my $arrayRef = \@array;
my $firstVal = $arrayRef->[0];
my $numVals = $#{$arrayRef} + 1;

my $aarray = [ 1, 2, 3..5 ];
my $firstVal = $aarray->[0];
my $numVals = $#{$aarray} + 1;

# complex data structurs
my $foo =
{
    bar => 123,
    baz =>
    {
        meier => 123,
        bla => [ 1, 2, 3, { x => 4 }, 'gugus' ];
    }
};
my $val = $foo->{bar}; # 123
my $val = $foo->{baz}->{meier}; # 123
my $val = $foo->{baz}->{bla}->[2]; # 3
my $href = $foo->{baz}; # { meier => 123, bla => [ 1, 2, 3, 4 ] }
my $val = $href->{meier}; # 123
my $val = $href->{bla}->[2]; # 3

# autovivification
if ($foo->{x}->{y}->{z})
{
    ...
}
# now $foo will look like (asking for ->{x}->{y}->{z} autovivified ->{x}->{y}):
# { bar => 123, baz => { meier => 123, bla => [ 1, 2, 3, 4 ] }, x => { y => {} } }
# hence you need to do instead:
if ($foo->{x} && $foo->{x}->{y} && $foo->{x}->{y}->{z})
{
    ...
}

# tricks (hashes are lists, too, => is little more than a ,):
my %hash = ( 'foo', 1, 'bar', 2 ); # same as ( foo => 1, bar => 2 )
my @array = ( foo => 1, bar => 2 ); # same as ( 'foo', 1, 'bar', 2 )
my %fixTypesLut = ( nofix => 0, drfix => 1, fix2d => 2, fix3d => 3 );
my %fixNamesLut = reverse %fixTypes; # ( 0 => 'nofix', 1 => 'drfix', 2 => 'fix2d', 3 => 'fix3d' )

# bad (because you don't know if somefunction() returns a list or a scalar):
my %hash => ( foo => somefunction() ); # that may fail dramatically or populate the hash with undesired stuff
# good:
my $foo = somefunction(); my %hash = ( foo => $foo );
# or if you must force scalar context:
my %hash => ( foo => ('' . somefunction()) );


# "filters and map" (list in ... list out)
my @bla = grep { $_ > 2 } (1, 2, 3, 4, 5); # --> (3, 4, 5)
my @bla = map { $_ + 1 } (1, 2, 3, 4, 5); # --> (2, 3, 4, 5, 6)
my @bla = grep { ... } map { ... }; # combine..
my @bla = map { $hash->{$_} } keys %hash; # (1, 2), same as "values %hash"
my @bla = sort { $hash{$a} <=> $hash{$b} } keys %hash; # ('foo', 'bar')


# see "perldata" document for more info (perldoc perldata)