PerlCramps has asked for the wisdom of the Perl Monks concerning the following question:

I am new to perl; But I am trying. I have a text file name hosts.txt with two lines hostone and hosttwo. I have created a sub
sub get_host { open( HOST, "<hosts.txt"); while(<HOST>) { my($line) = $_; chomp($line); print "$line\n"; return($_); } }
When I call the sub
my $host = get_host(); print "hostname = $host";
I am getting the following output
hostone hostname = hostone
I want to be able get the output for each line entry. any other help would be appreciated !!! Thanks

Replies are listed 'Best First'.
Re: Sub Return Help
by toolic (Bishop) on May 06, 2015 at 19:20 UTC
    Your code exits the sub after the 1st line of your file is read because the return is inside the while loop. This prints each host within the sub. Nothing is returned explicitly:
    use warnings; use strict; sub get_host { open( HOST, "<hosts.txt" ); while (<HOST>) { my ($line) = $_; chomp($line); print "hostname = $line\n"; } } get_host(); __END__ hostname = hostone hostname = hosttwo

      Thank you :)
      This helps me the value of the subroutine; I would like to be able to assign the subroutine to a variable call $host and use as need for other fuctions. Is that possible or am I approaching the process all wrong?? Thanks