top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Perl: Printing hash having undefined key

+2 votes
387 views

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 my_test.pl line 16, near "$k ("
Execution of my_test.pl aborted due to compilation errors.

Please point me where am I wrong?

posted Jun 23, 2014 by anonymous

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button

Similar Questions
+1 vote

I'm looking for a hash function and a related function or operator such that:

 H(string1 . string2) = f(H(string1), H(string2))
 H(string1 . string2) = H(string1) op H(string2)

 where:
 H() is the hash function    
 string1 is a string
 string2 is a string    
 . is the string concatenation operator 
 f() is a function
 op is a binary operator

Any suggestions?

+1 vote

I would retrieve my hash table when i pass it in argument at a function. In my case, function1 return my hash table, then i pass my hash table in argument to my function2 and in my function2 i would retrieve my hash table for browse it.

sub function1{
    my code;
    return %hash;
}

sub function2{
    my %hash=$_[0];
    my code browse my hash;
}

my %hash = function1();
function2(%hash);

I have the following error : Odd number of elements in hash assignment at

+1 vote
$ perl -le 'system "df -h"'
$ perl -le 'system "df","-h"'

Both two styles work fine. What's the difference between them and which is better usage?

+1 vote

I've a program that needs to print some fields formatted in different ways according to some conditions. The solution I come up is working, but I'm looking for a suggestion for something more elegant.

What I do is something like the following:

print sprintf $formats[ $condition ], @fields;

where $condition is the condition used to select a sprintf format string out of an array (@formats) that contains something like:

my @formats = (
 qw( %09d %-1s %03d ... )
, qw(%-4s %1s %09d %1s %-150s %-4s %011d)
, ...
);

Now, while this approach is working really fine, it is a little hard to decode, especially considering that I've got some formats with 50+ fields. I don't believe that using Perl formats is a solution, it will provide a quite longer configuration (consider I've got even fields specified as "-100%s"!).

Any suggestion to get a more readable code?

0 votes

How can write a python script which will execute some perl scripts in a gui and shouldn't be post processed....?

...