Hi Sunita,
In Perl hash keys can contain undef, blank space or a tab. All these
entities are valid and as a result it will print the key/value pair for the
undef also.
For clarity I have added the values 'blank space' and a tab in your example
Example 1:
========
[code]
@array = ("abc", 123, "dfg" ,456, "xsd", undef, "xyz", " ", "ajk", " ");
%hash = reverse @array;
foreach $k (keys %hash) {
print "key [$k] value [$hash{$k}]\n" if defined $k; #Added square
brackets for readability in the output
}
[/code]
[output]
key [] value [xsd]
key [ ] value [xyz]
key [ ] value [ajk]
key [456] value [dfg]
key [123] value [abc]
[/output]
Example 2:
========
[code]
#Printing the hash in a single line
print "key $_ value $hash{$_}\n" foreach (keys %hash);
[/code]
[output]
key value xyz
key 123 value abc
key value xsd
key value ajk
key 456 value dfg
[/output]
Hope it helps.
On Mon, Jun 23, 2014 at 12:49 PM, Sunita Pradhan <
[email protected]> wrote:
> Here is my code where i want to print one hash with one key undefined . I
> have condition print if key exist .
>
> I guess it should not print value for undefined key , but it does .
>
> #!/usr/bin/perl -w
>
> @array = ("abc", 123, "dfg" ,456, "xsd",undef);
> %hash = reverse @array;
>
> foreach $k (keys %hash){
> print "key $k value $hash{$k}\n" if(exists $hash{$k});
> }
>
> And another issue is , I want to write one line code for printing hash
> like below:
>
>
>
> *print "key $k value $hash{$k}\n" foreach $k (keys %hash);*But it fails
> with error :
>
>
> *syntax error at hash_test2.pl <http://hash_test2.pl> line 16, near "$k
> ("Execution of hash_test2.pl <http://hash_test2.pl> aborted due to
> compilation errors.*
>
>
> Please let me where I am going wrong .
>
> -Sunita
>
--
best,
Shaji
----------------------------------------------------------------------------------------------------------------------------------------------
Your talent is God's gift to you. What you do with it is your gift back to
God.
----------------------------------------------------------------------------------------------------------------------------------------------