Hello,

Few Perl questions if you please, regarding the optimal (Perlish) way to do 
things.
One constraint though: my code needs to run on old Perls (5.8 and up),
and can only use standard modules (so it doesn't help me if there's a CPAN 
module which does exactly what I need - I can't require the users to install 
it).

1. How to emulate Python's enumerate() function ?

Given a list, how to make a list of tuples with indexes/values ?

The non-perl way:
    my @list = ('A'..'Z');
    my @output;
    for (my @i = 0; $i < $#list ; ++$i) {
        push @output, [ $i, $list[$i] ];
    }

Perl way?
   my @output = map { [ $i, $list[$i] ] } ( 0 .. $#list ) ;

Is there a cleaner way (I can't use List::MoreUtils::pairwise sadly).


2. Given a hash with string-keys and numeric-values, how to return a list of 
the keys,
sorted by the values?
e.g
  my %h = ( "hello" => 4,
            "world" => 1,
            "foo" => 2,
            "bar" => 3 )
return:
   ( "world", "foo", "bar", "hello" )

I came up with:
   my @result =
           map { $_->[0] }
             sort { $a->[1] <=> $b->[1] }
               map { [ $_, $h{$_} ] }
                 keys %h;

Is there a better way?


3. How to automatically use the appropriate "cmp" or "<=>" ?
I have a function that accepts a list.
The list is either all strings, or all numbers.
Half-way through, the function needs to sort the list.
Is there a simple way to know whether to use "cmp" or "<=>" ?

I don't want to duplicate code with two functions, and would prefer to avoid 
adding an extra parameter to the function telling it if these are numbers or 
strings.

Thanks,
 -Assaf



_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to