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

how can i change directories to /etc and read in the service file to print out just the comments using a function?

janitored by ybiC: Retitle from less-than-descriptive "changing directories"

  • Comment on Change directories, Print just the comments

Replies are listed 'Best First'.
Re: Change directories, Print just the comments
by The Mad Hatter (Priest) on Dec 09, 2003 at 00:28 UTC

    There's no need to change directories, though you can do it with the chdir command.

    Here's some code that will do what you want:

    #!/usr/bin/perl use warnings; use strict; # # Open file for reading (explicit), die on error # open SERVICES, '<', '/etc/services' or die "cannot open /etc/services: $!"; # # Read thru each line (put into $_), and print the captured # comment text if the line has a comment (anything after a # # to the end of line). Note that this doesn't include the # hash (pound, octothorpe, et al.); move it inside the parens # for that behavior. # while (<SERVICES>) { print "$1\n" if /#(.*)$/ } # Close filehandle close SERVICES;

    Update Note in comment about not printing the hash mark.

Re: Change directories, Print just the comments
by Roger (Parson) on Dec 09, 2003 at 00:32 UTC
    No need to change to /etc directory if you only want to read the services file. Just use the full path to the services file.
    use strict; use warnings; use IO::File; my $f = new IO::File "/etc/services", "r" or die "can not read services file"; while (<$f>) { print "$1\n" if /(#.*)$/; }
    And you don't really need perl at all to do this on *nix -
    grep \# /etc/services | cut -f2 -d#
      While technically correct, I'd argue that there is no reason to bring IO::File into this (especially for the OP, who obviously doesn't need to mess with that module now). Perl's open will work just fine; why use a module when you don't need to?
        Well, IO::File is my preferred way for file I/O, I always use it unintentionally. I agree the OP is probably a bit green on Perl, but it shouldn't hurt to show him another way of openning files, should it. ;-)