Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl

How to return a value in Perl 5.34

Khizar Hayat Saani

To return a value from a subroutine, block, or do function in Perl, we use the return() function.

The following is the function syntax:

return Value

The Value may be a scalar, a list, or a hash value. Its context is selected at runtime.

If a Value is not provided, the function returns an empty list in a list context, undef in a scalar context, or nothing in a void context.

Types of return values

Code

# Subroutine for Welcome Message
sub Welcome($$)
{
	my($first, $last ) = @_;
	my $message = "Hello, $first $last!";
	
	# Return Value	
	return($first, $last, $message);
}

# Calling in Scalar context
$retval = Welcome("James", "Bond");
print ("Return value (scalar): $retval\n" );

# Calling in list context
@retval = Welcome("James", "Bond");
print ("Return value (list): @retval\n" );

In the above example, we define a simple subroutine that welcomes users using their first and last names, which are passed as input arguments.

The function returns the first and last names, as well as the welcome string. If the function is called via a scalar context declaring the return value with a preceding , only the welcome string is printed.

If the function is called in a list context declaring the return value with a preceding @, a list containing the user’s first and last names and the welcome string is returned.

# A subroutine to return a hash value.
sub get_welcome_messages {
  
  $hash{"Robert"} = "Hi, Bobby!";
  $hash{"James"} = "Welcome, Agent 007...";

  # Return Value
  return %hash;
}

# Calling in hash context
%loginMessages = get_welcome_messages;

foreach $key (keys %loginMessages) {
    print "$key => $loginMessages{$key}\n";
}

In the above example, we define a subroutine that returns a hash of usernames mapped onto welcome messages.

The function is called and the output is printed.

RELATED TAGS

perl

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring