I figure that your thinking is too complicated, especially when it comes to regex and processing the input lines.
Consider this code:
#!/usr/bin/perl
use strict;
use warnings;
while (my $line = <DATA>)
{
next if $line =~ /^\s*$/; # skip blank lines
$line =~ s/^\s*//; # remove leading spaces
$line =~ s/\s*$//; # remove trailing space and line ending
+
my ($name, @nums) = split /[\s-]+/, $line;
foreach my $num (@nums)
{
print "$name\t$num\n";
}
}
# PRINTS
#abcd 723
#abcd 724
#abcde 552
#abcde 554
#abcde 553
#abcdef 756
__DATA__
abcd 723-724
abcde 552-554-553
abcdef 756
I don't think the trim leading and trailing spaces statements are needed here given your DATA. However, you should become familiar with how to do that.
Update: As a general rule:
- Use Regex when you know what to keep.
- Use Split when you know what to throw away.
This code works the same:
#!/usr/bin/perl
use strict;
use warnings;
while (my $line = <DATA>)
{
next if $line =~ /^\s*$/; # skip blank lines
my ($name, @nums) = $line =~ /(\w+)/g;
foreach my $num (@nums)
{
print "$name\t$num\n";
}
}
# PRINTS
#abcd 723
#abcd 724
#abcde 552
#abcde 554
#abcde 553
#abcdef 756
__DATA__
abcd 723-724
abcde 552-554-553
abcdef 756
I almost always have a statement to throw away blank lines. They can often appear at the end of a file and hard to see when you just type or cat the file.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|