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

I have a subroutine
sub get_service { open (SERVICES, "/etc/services") || die "$!\n"; while (my @SVCS=<SERVICES>) { foreach $_(@SVCS) { chomp ($_); next if ( $_ =~ m/^#+(\s+)?/ ); #skip comments@ beg of line my ($name,$port,undef)=split(/\s+/,$_); next unless ( $port =~ m/\d{1,}\/(tcp|udp)/i ); my ($portnum,$proto=split(\//,$port); } } }

here is where im stuck - I want to return the data to the main program. Would it be better to write

my %service=($name,[$portnum,$proto]);


or just return the values of $name, $portnum, and $proto for each lookup of $name from the main program?

Thanks

Replies are listed 'Best First'.
Re: returning values from a sub
by Fletch (Bishop) on Jan 06, 2005 at 19:11 UTC

    If you're just going to stick things in another hash when you get it back it makes much more sense to return a list of the three values (or even two, the name and an arrayref).

    Of course in this particular case the more sensible thing would to be to use getservbyname rather than rolling your own and possibly encountering problems on hosts which are using NIS/YP . . .

      ahhh... I just found getservbyport...
      Thanks!
      getservbyname just returns a port number, Ill already have the port number and possibly the protocol, Ill need the service name returned...
Re: returning values from a sub
by fauria (Deacon) on Jan 06, 2005 at 19:57 UTC
    Hi!

    Maybe this way is useful for you:

    use strict; use Data::Dumper; sub getServices{ my $file = "/etc/services"; open SVCS, $file or die "Error opening $file: $!"; my $services; while( <SVCS> ){ my %hash; next if $_ =~ /^\#/ or $_ =~ /^\s/; my ($name, $port_proto) = split /\s+/, $_; my ($port, $proto) = split /\//, $port_proto; %hash = ( protocol => $proto, port => $port ); $services->{$name} = \%hash; } close SVCS; return $services; } my $returned = &getServices; print Dumper $returned; print "Protocol for service FTP: $returned->{ftp}->{protocol}\n";


    Regards