I want to read the following file into a hash, minus the comment lines (#):

You should read perlopentut for an intro to interacting with files if you are not familiar with opening and reading files. I would read the file in line by line. I would then use next to skip lines starting with '#'. Finally, I would split on a semicolon with a maximum of two terms, based on what you've posted. See perlretut if you are not familiar with regular expressions - they are a core part of Perl and incredibly powerful once you get the hang of them.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %data; while my $line (<DATA>) { next if $line =~ /^#/; my ($key,$value) = split /:/, $line, 2; $data{$key} = $value; } print Dumper \%data; __DATA__ # config file port: 8888 logfile: /data/log

how would I reference the port number in the hash one the above file is read in?

The short answer is yes. In general, for this sort of question, you should write up a small test script to test the answer in a script. It is also discussed in perldata, the intro to Perl data types.

As a side note, please wrap all code, input and output in <code> tags so things do not get mangled between posting and display. See Writeup Formatting Tips.


In reply to Re: Read a file into a hash by kennethk
in thread Read a file into a hash by fritz1968

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.