| |||||||
|
|
Click here to download plain text source code.
# subroutine name: struct2text # Input: # $struct - reference to any perl structure (no loops allowed!!!) # $store_empty_values - store hash pairs with empty values or not # $separator_char - lines separator (default is "\n"), used to write # structure in one line # Returns: string, which represents passed data structure in Perl language # Usage example: struct2text( {"key1" => "val1", "key2" => "val2", # "empty_value_key" => "", # "arr_key" => [4,5,6,8,"abc"]}, # 1, "\n"); # Result: ' # {"arr_key"=>["4", # "5", # "6", # "8", # "abc", # ], # "empty_value_key"=>"", # "key1"=>"val1", # "key2"=>"val2", # }' sub struct2text { my ($struct,$store_empty_values, $separator_char) = @_; $separator_char = $separator_char || "\n"; my $res=""; my $ref_name = ref($struct); if (! defined $struct) { $res="undef"; } elsif ($ref_name eq "SCALAR") { $res=perl_quote(${$struct}); } elsif ($ref_name eq "ARRAY") { $res="["; foreach (@{$struct}) { $res.=struct2text($_,$store_empty_values, $separator_char).",".$separator_char; }; $res.="]"; } elsif ($ref_name eq "HASH") { $res=$separator_char."{"; foreach (sort keys %{$struct}) { $res.=perl_quote($_)."=>".struct2text(${$struct}{$_},$store_empty_values, $separator_char).",".$separator_char if (${$struct}{$_} || ${$struct}{$_} ne "" || $store_empty_values); }; $res.="}"; } elsif ($ref_name eq "REF") { $res="\\".struct2text(${$struct},$store_empty_values,$separator_char); } else { $res=perl_quote($struct); } return $res; } sub perl_quote { my ($str) = @_; $str=~s/(["\\\@\$])/\\$1/gs; $str=~s/\r\n/\n/gs; $str=~s/([\x00-\x1F])/sprintf("\\x%02x",ord($1))/egs; "\"$str\""; } |
|||||||||||||||||||||
| Copyright © 1999-2007 Atomicsoft Ltd. All Rights Reserved. | ||