When trying to compare two values, $x and $y, for example, to test for equivalence, you can use
eq on them only if both values are defined. If you're not careful, you get warnings. This means you can't just do:
($x eq $y)
In fact, it looks like you have to go to some great lengths to work around this:
((defined($x) && defined($y) && ($x eq $y))
|| (!defined($x) && !defined($y))
That's a lot of code for something that should be pretty simple. It's worse when $x and $y aren't simple variables. They could be part of a structure which contains a series of "Original" (O) and "Current" (C) values:
my $foo = {
aa => { O => 'zz', C => 'yy' },
bb => { O => 'xx', C => 'xx' },
cc => { O => undef, C => 'ww' },
dd => { O => 'vv', C => undef },
ee => { O => undef, C => undef },
ff => { C => undef },
gg => { O => 0, C => 0 },
hh => { O => undef, C => 0 },
};
How compact can a function be that, when given a HASH reference, returns a list of those entries which have changed. In other words, where the 'original' is not the same as 'new'. As a note, the 'new' value is always present, even if it is
undef.
By stepping outside of traditional boolean logic, by throwing in a few of those ternary operators, I managed to get this monstrosity:
sub f
{
my ($h) = @_;
grep
{
!exists($h->{$_}->{O})
|| (defined($h->{$_}->{O})?
(defined($h->{$_}->{C})?
($h->{$_}->{O} ne $h->{$_}->{C})
: 1)
: defined($h->{$_}->{C}))
} keys %$h
}
This returns 'aa,cc,dd,ff,hh', or those values which differ from O to C.
Since warnings are supposed to be avoided,
use strict; use warnings;
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.