Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: capture optional text

by Anonymous Monk
on May 17, 2017 at 22:03 UTC ( [id://1190507]=note: print w/replies, xml ) Need Help??


in reply to capture optional text

use strict; use warnings; use Data::Dumper; my %hosts; while (chomp(my $line = <DATA>)) { my ($key,$val) = split /\s+/, $line, 2; $hosts{$key} = $val; } print Dumper \%hosts; __DATA__ XYZ1ADAIQ1 #AMI XYZ1ADECQ1 #OAG XYZ1ADEDQ1 XYZ1ADEDQ2 ##DMS Host

Replies are listed 'Best First'.
Re^2: capture optional text
by haukex (Archbishop) on May 18, 2017 at 13:55 UTC
    while (chomp(my $line = <DATA>)) {

    This won't work if the final line doesn't end on a newline, as chomp returns the number of newlines it removed. Better to use the traditional while (<DATA>) { chomp; ... or while (my $line = <DATA>) { chomp($line); ... Update: Plus, even with a trailing newline, the code generates a warning, since after the final line, the loop condition is executed one more time, and <DATA> will return undef and chomp(my $line = undef) causes a warning.

Re^2: capture optional text
by Lotus1 (Vicar) on May 18, 2017 at 13:32 UTC

    Split should have been my first choice but I didn't think of it. Very nice, thanks.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1190507]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-24 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found