Getting HASH ref error in Perl -


I am trying to understand why I get a hash ref error in one situation and not another. Error: string ("1") can not be used as a HASH referrer, while "hard reef" can be used in ./a.pl on line 351. & Lt; -

Problem code:

  My $ count = 0; My% sort_total; Do my $ host (keys% ips_per_host) before (my key% {$ ips_per_host {$ host}}) {$ sort_total {$ count}} = $ ips_per_host {$ host} {$ ip}; $ Sort_total {$ count} {'host'} = $ host; & Lt; - $ sort_total {$ count} {'ip'} = $ ip; $ Count ++; }} Foreach $ count (sort {$ sort_total {$ a} cmp $ sort_total {$ b}} key% sort_total) {[...]}  

However, if I make another Hash and instead, there is no error.

  My $ count = 0; My% sort_total; My% sort_hosts; Do my $ host (keys% ips_per_host) before (my key% {$ ips_per_host {$ host}}) {$ sort_total {$ count}} = $ ips_per_host {$ host} {$ ip}; $ Sort_hosts {$ count} {'host'} = $ host; $ Sort_hosts {$ count} {'ip'} = $ ip; $ Count ++; }} Foreach $ count (sort {$ sort_total {$ a} cmp $ sort_total {$ b}} key% sort_total) {[...]}  

Can someone help me I understand why this happens? I have run it on many occasions, and I really want to wrap my head around it.

You are getting this error because this expression is:

  $ Ips_per_host {$ host} {$ ip}  

returns the number 1 . It's a great thing to store in $ sort_total {$ count} , which you do.

The problem is that you can again $ sort_total {$ count} {'host'} .

When you use a nested data structure, then Pearl will try to "automatically run" the layers of the structure needed for the existence of the nested object. So Pearl sees that if $ sort_total {$ count} is present, and it does it then checks whether that value is a reference to another hash because your expression has two-level hash . But this is not; It is already set to the value 1 if the pearl was to make a hash context automatically, then it will erase what you have already stored, which is probably not what you Want to So Pearl comes out of an error, assuming that you will correct it instead of overwriting your data.

So there are some options.

    If there is indeed a Hashref return and no number, then it is a bug, if $ Ips_per_host {$ host} {$ ip} So fix it.

  1. If the $ ips_per_host {$ host} {$ ip} is actually considered to be a number, then use it to use it in a hash Assign a key, such as $ sort_total {$ count} {per_host} = $ ips_per_host {$ host} {$ ip};

  2. Use two different hashes like you are now doing.


Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -