On Tue, Jul 8, 2014 at 9:31 PM, Assaf Gordon <[email protected]> wrote:

> 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).
>

There's nothing wrong with your solution. Your code does what you want, and
fits the requirements you gave (it doesn't use a different module). What
don't you like about it?




>
>
> 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?
>

This is fine.


>
>
> 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.
>

sub untested_solution {
  my @input = @_;
  return if @input == 0;
  # We were promised the input is at least consistent, so sniff the first
element.
  my $cmp = looks_like_a_number($input[0]) ?
      sub { $a <=> $b } : sub { $a cmp $b };
  return sort $cmp, @input;
}

# You could find a better implementation of this. Probably mucking around
the C API
# there's even a "correct" (more or less) way, but it sounds like you can't
use modules.
sub looks_like_a_number {
  my ($x) = @_;
  no warnings;
  return $x eq $x+0;
}



>
> Thanks,
>  -Assaf
>
>
>
> _______________________________________________
> Perl mailing list
> [email protected]
> http://mail.perl.org.il/mailman/listinfo/perl
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to