in reply to Transferring hash keys to array... Need help sorting

#!/usr/bin/perl # http://perlmonks.org/?node_id=1188504 use strict; use warnings; my %hash = qw( title1 1 title3 3 title4 4 title2 2 ); my @labels = sort keys %hash; my @content = @hash{@labels}; use Data::Dumper; print Dumper \%hash; print "\n"; print Dumper \@labels; print "\n"; print Dumper \@content;

Replies are listed 'Best First'.
Re^2: Transferring hash keys to array... Need help sorting
by DARK SCIENTIST (Novice) on Apr 21, 2017 at 03:14 UTC
    In this instance, this would work. But what if the content for each element of that array is a string of characters and not numeric? (i.e. accaccacacaca)

      Like this? Works fine.

      #!/usr/bin/perl # http://perlmonks.org/?node_id=1188504 use strict; use warnings; my %hash = qw( title1 one title3 three title4 four title2 two ); my @labels = sort keys %hash; my @content = @hash{@labels}; use Data::Dumper; print Dumper \%hash; print "\n"; print Dumper \@labels; print "\n"; print Dumper \@content;
        This could work. I'm going to try and implement it tonight
      ... what if the content for each element of that array is a string of characters and not numeric?

      One interpretation:

      c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my %hash = qw(title1 uno title3 tres title4 quatro title2 dos); ;; my @labels = sort keys %hash; my @content = @hash{@labels}; ;; dd \%hash; dd \@labels; dd \@content; " { title1 => "uno", title2 => "dos", title3 => "tres", title4 => "quatr +o" } ["title1", "title2", "title3", "title4"] ["uno", "dos", "tres", "quatro"]
      (BTW: This is something you could actually have tried for yourself!)

      Update: The  @hash{@labels} thing is a hash slice.


      Give a man a fish:  <%-{-{-{-<

        Hash slices are a new concept for me but I will give this a try as well as the other suggestions everyone has added here