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;
![Dynamic](https://i.stack.imgur.com/wAh9i.png?s=256&g=1)
Author by
Dynamic
Updated on July 08, 2020Comments
-
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 almost 13 years
say for keys %hash;
in post 5.10 -
Dynamic almost 13 yearsIs there a way to put that into a Perl/Tk program?
-
Dynamic almost 13 yearsIs there a way to put that inside of a Perl/Tk program?
-
Keith Thompson almost 13 years@perl.j: It's straightforward Perl; why wouldn't it work in a Perl/Tk program?
-
Dynamic almost 13 yearsWell I am trying to put it in as the text in a messageBox but it isn't working. Any suggestions?
-
TLP almost 13 years@perl It's not really possible to answer such a question without seeing the code.
-
Dynamic almost 13 yearsWell 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 almost 13 yearsPut this in:
join "\n", keys %hash
. It's a very different question from the one you asked. -
Dynamic almost 13 years@TLP: Thank You so much. You're great! +1 for you!
-
musiKk almost 13 yearsI 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 almost 13 yearsTurns 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 almost 8 yearsThe
map
function is there to transform a list. If you are usingmap
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 aforeach
loop instead (for exampleprint "$_\n" foreach keys %hash
would work here). An alternative that usesmap
as intended might beprint map { "$_\n" } keys %hash
.