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.


In reply to Re: Hash (not) returned by subroutine by tobyink
in thread Hash (not) returned by subroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.