As others have commented here, you have a deceptively tricky bit of work here to parse out this data because of the commas both inside and outside the quotes. If you have control over the format of testhash.txt you should consider changing that. An easy-to-parse format would be to separate key-value sets each on their own line. Thus:
key1,value1 key2,value2 key3,value3 key4,value4
On the other hand if you need to use the file as it is, and if you know it will always have exactly four key-value pairs in the format you have given, this code will allow you to parse it into a hash.
open HANDLE, 'testhash.txt' or die "Can't open: $!"; my $data = <HANDLE>; close HANDLE; chomp $data; my %hash = $data =~ /'([^,]+),([^']+)', '([^,]+),([^']+)', '([^,]+),([^']+)', '([^,]+),([^']+)'/x; # demo use of the hash to access results foreach my $key (keys %hash) { print "$key $hash{$key}\n"; }
It ain't elegant or flexible, but it will satisfy your immediate need. If there are going to be spaces after the commas or other interesting things, that can be dealt with in this approach. But at a certain point, you would need to consider a more robust approach (i.e. a CSV module from CPAN). Which would be a bit of overkill just to grab four key-value pairs.

In reply to Re: How can I read a line of text from a file into an array? by dvergin
in thread How can I read a line of text from a file into an array? by fenners

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.