Printing Perl Hash Keys

47,647

Solution 1

Does this do it for you?

print "$_\n" for keys %hash;

Solution 2

Short version:

$, = "\n";
print keys %hash;

Or inside a larger script:

{
    local $, = "\n";
    print keys %hash;
}

To put it in a variable, for printing in a message box in accordance to your comments:

my $var = join "\n", keys %hash;
Share:
47,647
Dynamic
Author by

Dynamic

Updated on July 08, 2020

Comments

  • Dynamic
    Dynamic almost 4 years

    I am trying to print out my Hash Keys in Perl, one per line. How would I go about doing this?

  • Zaid
    Zaid almost 13 years
    say for keys %hash; in post 5.10
  • Dynamic
    Dynamic almost 13 years
    Is there a way to put that into a Perl/Tk program?
  • Dynamic
    Dynamic almost 13 years
    Is there a way to put that inside of a Perl/Tk program?
  • Keith Thompson
    Keith Thompson almost 13 years
    @perl.j: It's straightforward Perl; why wouldn't it work in a Perl/Tk program?
  • Dynamic
    Dynamic almost 13 years
    Well I am trying to put it in as the text in a messageBox but it isn't working. Any suggestions?
  • TLP
    TLP almost 13 years
    @perl It's not really possible to answer such a question without seeing the code.
  • Dynamic
    Dynamic almost 13 years
    Well I would hate to put all that code in a comment show the area of concern: sub show_index { my $index = $mw->messageBox(-type=>"ok", -icon=>"info", -message=> -title=>"Index"); } The blank message area is where I want the code.
  • TLP
    TLP almost 13 years
    Put this in: join "\n", keys %hash. It's a very different question from the one you asked.
  • Dynamic
    Dynamic almost 13 years
    @TLP: Thank You so much. You're great! +1 for you!
  • musiKk
    musiKk almost 13 years
    I don't think one should use $,. I mean, I like it too but I fear that most people would have to look it up.
  • TLP
    TLP almost 13 years
    Turns out, OP didn't want to print the keys at all, so the solution is the "join" thing, not the $, part. Besides, what's wrong with using such variables? They are there for a reason.
  • Dave Cross
    Dave Cross almost 8 years
    The map function is there to transform a list. If you are using map in void context (i.e. if you're not using the return value) then you're using it wrong and should probably switch to using a foreach loop instead (for example print "$_\n" foreach keys %hash would work here). An alternative that uses map as intended might be print map { "$_\n" } keys %hash.