in reply to foreach - adding newlines?
The keys issue is that chomp was chomping the default variable ($_). Most likely if you had used strictures (use strict; use warnings;) you'd have received warnings about chomping an undefined value. added: The other part of the sting is that your "push" adds two entries to the array where you really need one entry that is the concatenation of the two value strings.
However, there is some scope for a little tidying of your code. Consider:
use strict; use warnings; my $events = <<'END_EVENTS'; d1:v1 d2:v2 d4:v4 d1:v1 d2:v2 d4:v4 END_EVENTS open my $eventsIn, '<', \$events or die "Failed to open event file: $! +"; my $d2_value; my $d1_value; my @eventList; while (<$eventsIn>) { chomp; my $title; if (m/d1/i) { ($title, $d1_value) = split /:/; } elsif (m/d2/i) { ($title, $d2_value) = split /:/; } elsif (m/d4/i) { push @eventList, "$d1_value$d2_value\n"; } } close $eventsIn; print @eventList;
Prints:
v1v2 v1v2
Don't worry about the $event stuff - that's just to make a stand alone example without needing an external file.
Note the use of the three parameter open and the use of 'or die' to check the result and report errors. Use a lexical file handle ($eventsIn) rather than a bare word file handle (EVENTS_IN).
Use a while loop and handle things line by line. This code makes an end run around your chomp issue by actually using the default variable ($_) to store the line just read.
Declare variables in the smallest scope you can - $title is only used inside the loop so that is where it is declared. The other variables require a lifetime that is longer than one loop iteration so they are declared outside the loop.
To achieve the output you want you need to concatenate your two value strings and push the result. Your original code effectively pushed the two values into the array - you could do it that way, but printing becomes messy.
The current code is likely to fail in nasty ways if the input data is not exactly as you expect it to be. You should think hard about better validation techniques!
|
|---|