Posts

Showing posts with the label Perl

In Perl keys get defined if they are accessed as hash, without checking for their existence

In the following code snippet, 'c' is not as key in 'foo' but is set to {} when the last check for foo->c->0 is called. / tmp ( ) $ cat foo . pl use strict ; use warnings ; use Data : : Dumper ; sub abcde { my $foo = { 'a' = > 1 , 'b' = > 2 } ; print Dumper ( $foo ) ; if ( exists $foo - > { c } & & defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; if ( defined $foo - > { c } and defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; if ( defined $foo - > { c } - > { 0 } ) { print "C is defined" ; } print Dumper ( $foo ) ; } abcde ( ) ; / tmp ( ) $ perl foo . pl $VAR1 = { 'a' = > 1 , 'b' = > 2 } ; $VAR1 = { 'a' = > 1 , ...

Loop over an array with index and element in the array

Perl looping of an array with index as well as the item stored in variables, /tmp$ cat loop_with_index.pl  my @arr=(1,2,3,4); while (my ($i, $x) = each(@arr)) {     print "$i: $x\n"; } /tmp$ perl loop_with_index.pl  0: 1 1: 2 2: 3 3: 4

Perl constant hashrefs are actually functions

To get the keys of a constant hashref you first need to learn that a constant is actually a function and hence use () to get the keys from it INPUT: $ cat perlConstant.pl use Data::Dumper; use constant FOOHASH => { "foo" => "bar", }; print FOOHASH->{"foo"}."\n"; foreach $key (keys %{FOOHASH()}) { FOOHASH->{$key} = "bar1"; } print FOOHASH->{"foo"}."\n"; foreach $key (keys %{FOOHASH}) { FOOHASH->{$key} = "bar2"; } print FOOHASH->{"foo"}."\n"; OUTPUT: $ perl perlConstant.pl bar bar1 bar1