LINUX.ORG.RU

Как работает это в perl?

 , , , ,


1

1

В programming perl есть пример:

$table = {
            "john" => {age => 47,
                       eyes => "темно-карие",
                       weight=>186,
                      },
            "mary" => {age => 23,
                       eyes => "карие",
                       weight=>128,
                      },
            "bill" => {age => 35,
                       eyes => "голубые",
                       weight=>157,
                      },
};

Как отсортировать это?

Порядок пар key - value в hashref не гарантируется.

По какому критерию хочешь отсортировать?

P.S. По итогу в любом случае будет массив, вместо хеша, если важен именно порядок.

KernelPanic
()
Последнее исправление: KernelPanic (всего исправлений: 1)

Я бы посмотрел вот в эту сторону:

@byval = sort { $h{$a} cmp $h{$b} } keys %h;   # список ключей хеша, отсортированный по значениям хеша

Пруфлинк: https://stepik.org/lesson/51552/step/7?unit=29818 (там еще много интересных намеков, похоже нужна регистрация чтобы посмотреть по ссылке).

Infra_HDC ★★★★★
()
Ответ на: комментарий от gremlin_the_red

У меня почему-то не взлетело:

user@host:$ ./0001.pl 
Experimental keys on scalar is now forbidden at ./0001.pl line 18.
user@host:$ perl --version

This is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi
(with 90 registered patches, see perl -V for more detail)

Copyright 1987-2017, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

user@host:$ cat ./0001.pl | head -18 | tail -1
@lst = sort { $table->{$a}{age} <=> $table->{$b}{age} } keys $table;
Infra_HDC ★★★★★
()