PDA

View Full Version : Comparing undefined values in perl



adhawkins
2016-05-20, 03:18
Hi,

This is a very basic Perl question, apologies if it sounds a bit newbie! I'm a proficient programmer, but haven't really done any Perl for several years.

In my plugin, I've got a suspicion that a comparison I'm doing against two variables isn't quite working correctly. When the plugin is first installed, none of the preferences are defined.

In my preferences handling code:

https://github.com/adhawkins/SimpleLibraryViews/blob/master/SimpleLibraryViews/Settings.pm

(around line 57)

I do:


if ( $prefs->get('libraries') ne $params->{'pref_libraries'} ) {


and if they're different, I proceed to save the new preference and update the virtual libraries. At this point, I see warnings in the server log about comparison of an undefined variable (presumably because $pres->get returns undef), and I'm not 100% sure it then proceeds into the if block.

Is it legal to compare an undefined value with one that is defined? If so, will 'ne' report that they are different? Or should I be either explicitly checking for undef, or perhaps setting a default value for 'libraries' the first time the plugin is run?

Thanks

Andy

mherger
2016-05-20, 04:34
Prefs by default aren't defined, obviously. $prefs->get('somename') therefore does not return a defined value before you set one. To make sure there is one, you can do something like this in initPlugin:


$prefs->init({
somename => ''
});


This would initialize the value with an empty string. It's still empty, but defined.

'ne' is a string comparison. And a string is only a string when it is defined.

adhawkins
2016-05-20, 06:27
Hi,

So would 'undef ne "something"' be considered true, or false?

Thanks for the tip regarding $prefs->init. Would this only occur if the preference wasn't already set?

Andy

mherger
2016-05-20, 06:55
> So would 'undef ne "something"' be considered true, or false?

I guess it's undefined, as it's an invalid comparison. I'd have to
google it.

--

Michael

adhawkins
2016-05-20, 07:09
Ok, sounds like that might be the cause of what I think I was seeing then.

Can you answer the question about $prefs->init() ? Can I just call that all the time in initPlugin, or do I need to check if it's defined first?

Thanks

Andy

mherger
2016-05-20, 08:22
> Can you answer the question about $prefs->init() ? Can I just call that
> all the time in initPlugin, or do I need to check if it's defined
> first?

No, that's exactly what $prefs->init() does: initialize with your
default value, unless it's already defined.

--

Michael

adhawkins
2016-05-20, 08:34
Excellent, I'll give that a whirl then.

Thanks

Andy