Ask Your Question
0

How do I initialize a variable based on its type?

asked 2013-04-04 14:25:38 -0500

redmine gravatar image

updated 2013-04-04 16:39:32 -0500

llowder gravatar image

How do I initialize a variable in a define type? If

 variable = string           
 variable = list           
 variable = boolean

Also when should we use [] , "" and undef to initialize?

I was using undef for initialization , irrespective of variable type. Is it a wrong approach ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2013-04-04 16:48:28 -0500

llowder gravatar image

If you use stdlib you can do the following:

if is_string($variable) {
  ...
} elsif is_array($variable) {
  ...
} elsif is_hash($variable) {
  ...
} elsif is_boolean($variable) {
 ...
} else {
 ...
}

As far as for initialization, I think you are misunderstanding how variables work. undef is special, and is suitable if you want to set the default for a param, but don't want to give it an actual value.

"" and '' are both empty strings, they are not the same things as undef. In the same vein, [] is an empty array and {} is an empty hash.

Which one you use will depend on how you want to structure your ... (more)

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-04-04 14:25:38 -0500

Seen: 426 times

Last updated: Apr 04 '13