Hello Lennotoecom,

I would re-write this idea as follows:

#! perl use strict; use warnings; use List::Util 'max'; my %h = ( '11c' => 'C', b => 'B', e22 => 'E', aaaaa => 'AAAA', ); if (%h) { my $last = max map { \$_ } values %h; printf "The last element added to the hash was %s\n", $$last; } else { print "No elements have been added to the hash\n"; }

This gives the same result, but:

This script’s output (like the title of this node) is still somewhat misleading, however, as “last element added” really means “last element added of those still remaining in the hash.” For example, if you add elements X, Y, and Z, and then delete element Z, this script will output Y as the “last element added,” which isn’t strictly correct.

But the real problem with this whole strategy is that it relies on an implementation detail of the perl interpreter; namely, that it always assigns new hash values to memory addresses above those of previously-assigned values. Is this guaranteed to be the case? Will it always be true of perl implementations in the future? I don’t know, and for that reason I would advise against this approach until and unless it can be proven to be valid now and also future-proof.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: the last added element of a hash by Athanasius
in thread the last added element of a hash by Lennotoecom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.