Wednesday, March 9, 2011

Perl: accessing array from hash of arrays

Recently i came across an interesting problem in Perl.
Specifically, i was trying to access array from hash of arrays.

use strict;

my %oHash = ("one" => [1,2,3], "two" => [4,5,6], "three" => [7,8,9]);

OK. lets write function to output this hash.

sub print_hash {
    for my $key ( keys %oHash ) {
        print "$key: ";
        for my $i ( 0 .. $#{ $oHash{$key} } ) {
            print " $i = $oHash{$key}[$i]";
        }
        print "\n";
    }
}

Now if you call this sub you should see something like this:

three:  0 = 7 1 = 8 2 = 9
one:  0 = 1 1 = 2 2 = 3
two:  0 = 4 1 = 5 2 = 6

So printing is easy, but the problem is how to modify values of arrays (lets say array "one").

We need to create reference to array and here is magic part:

my $arr = \@{$oHash{"one"}};

Yes, that's it.

foreach(@{$arr}) {

    print $_ . "\n";
    $_ = 7; # modifying value
}

Done.

Saturday, November 21, 2009

Django : passing list of objects to template

in views.py:

object_list = [obj0, obj1, obj2]
context = {'object_list' : object_list }
return direct_to_template(request, 'path_to_template.htm', extra_context = context)
in path_to_template.htm:

{{ object_list.0.attrib }} #access to obj0.attrib  
{{ object_list.2.attrib }} #access to obj2.attrib 
etc.

Python : Generate random values from the list

import random

_list = ["item_1", "item_2", "item_3"]
random_value = random.choice(_list)

Tuesday, November 17, 2009

my django notes

Some basics django notes:

Creating new app:
@python manage.py startapp app_name

DB sync:
@python manage.py syncdb

Run development server:
@python manage.py runserver