G'day ultranerds,

Just put braces around $foo in your hash slice. [That's not strictly correct — see Update (Clarification) below.]

#!/usr/bin/env perl use strict; use warnings; my $foo = { testing => 'bar', test => 'test2', something => 'test3' }; delete @{$foo}{qw(testing something)}; use Data::Dump; dd $foo;

Output:

{ test => "test2" }

Update (Clarification)

In your OP, you have:

"I know if it was just a simple hash, I could delete multiple fields with: delete @$foo{qw(testing something)} ..."

If that was a "simple hash" (e.g. %foo), then the detete statement would need to have "@foo", not "@$foo".

I suspect having seen "simple hash", my eyes glossed over the $ before foo and some mental confusion ensued.

So, the delete statement you showed would have worked fine for a hashref (e.g. $foo) but not for a hash (e.g. %foo); and, my statement, "Just put braces around $foo ...", wasn't strictly correct in that it didn't address your problem even though it was valid syntax which achieved the end result you were looking for.

To quickly summarise the syntax for specifying a hash slice:

While I typically write %$hashref, @$arrayref and even $#$arrayref, I do tend to use braces for anything more complex, including slices.

[If you're interested, Perl Best Practices recommends putting braces around references in all of those (i.e. %{$hashref}, @{$arrayref} and $#{$arrayref}). Obviously, I don't follow all of the Perl Best Practices. :-)]

-- Ken


In reply to Re: Remove multiple fields from hashref? by kcott
in thread Remove multiple fields from hashref? by ultranerds

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.