Further to soonix's answer, if you wish to not return anything from a function, use:
sub get_data {
...;
return; # undef in scalar context or the empty list in list conte
+xt
}
or:
sub get_data {
...;
return undef; # undef in scalar context and a one-item list conta
+ining undef in list context
}
Usually the former is preferred.
For object-oriented modules, if you don't have anything useful to return for a method, return $self is a good idea because it allows method calls to be easily chained, like:
sub enable_warnings {
my $self = shift;
$self->{warnings} = 1;
return $self;
}
sub enable_errors {
my $self = shift;
$self->{errors} = 1;
return $self;
}
sub disable_warnings {
my $self = shift;
$self->{warnings} = 0;
return $self;
}
sub disable_errors {
my $self = shift;
$self->{errors} = 0;
return $self;
}
sub run_process {
my $self = shift;
...;
return $result;
}
# Now instead of doing this:
$widget->enable_warnings;
$widget->enable_errors;
my $result = $widget->run_process;
# We can do this:
my $result = $widget->enable_warnings->enable_errors->run_process;
A final note. Doing this:
sub bleh {
return $result;
}
Is actually very slightly slower than:
sub bleh {
$result;
}
So if you have a small function that gets called a lot and you want to optimize, removing return and just allowing the last value evaluated to fall through as the return value may give you a slight boost.
|