Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a builtin "hash to string" in Perl?

Tags:

string

hash

perl

I'm coming to learn Perl from a Python background where the following hash-to-string conversion is built in to the language:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> str(d)
"{'a': 1, 'c': 3, 'b': 2}"

Is there a builtin and/or module that has a subroutine with output along the lines of:

"('a' => 1, 'b' => 2, 'c' => 3)"

Strangely, a web search for perl "hash to string" doesn't turn up anything along the lines I'm looking for. Thanks!

like image 567
cdleary Avatar asked Jan 19 '09 23:01

cdleary


People also ask

Is hash empty Perl?

From perldoc perldata: If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.

What is a hash in Perl?

A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Hash variables start with a '%' sign. Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values can either be a number, string or reference.

How do I read a hash file in Perl?

use Data::Dumper; use File::Slurp; my %hash = read_file("output.pl"); print Dumper(keys(%hash));


1 Answers

use Data::Dumper;
local $Data::Dumper::Terse = 1;
my $str = Dumper({a => 1, b => 2, c => 3});
like image 125
Leon Timmermans Avatar answered Sep 19 '22 20:09

Leon Timmermans