Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: defined vs null string

by cdarke (Prior)
on Aug 30, 2011 at 14:50 UTC ( [id://923246]=note: print w/replies, xml ) Need Help??


in reply to defined vs null string

Y is not defined and but it equates to a null string. How does the Perl concepts compare to a language like C

The closest thing in C to an undefined value is when a variable is not initialised. For example:
int x; printf("%d",x);
will give you whatever junk is in memory, it is unlikely that the value will be zero. In Perl we don't have that problem, every scalar has the value undef until you assign it otherwise. This can be flagged as an error or warning should you want it (that's one reason for use warnings and use strict).

Worse, an unitialised string in C can cause your program to crash:
char name[42]; printf("%s",name);
could cause printf to run into an address which is illegal and crash the program. It might not - it might hit a zero delimiter by coincidence, but then you get junk displayed. No such problems in Perl.

A "null string" is, I assume, an empty string, 0x00 in C. One difference with C is that even a null string will require an array of at least one byte. char *pName = NULL; is not an empty string in C, it is a pointer with a value of zero. That might be semantics, but in C (not in C++) NULL is a pointer value.

Take a look at a Perl scalar string variable using Devel::Peek::Dump. Dump the variable as you change its size, and look at the amount of memory used (LEN). Now undef the value and see the difference:
use strict; use warnings; use Devel::Peek; my $str = ""; Dump($str); $str = "Fred Bloggs"; Dump($str); $str = "This is a much, much longer string"; Dump($str); $str = ""; Dump($str); undef $str; Dump($str);
See the difference between setting a string to be empty and using undef. Would it have made a difference if you assigned undef to the string instead of using undef as a function?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://923246]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-24 11:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found