On Wed, Jan 14, 2004 at 09:57:51PM -0600, James Edward Gray II ([EMAIL PROTECTED]) wrote:On Jan 14, 2004, at 7:22 PM, Jose Malacara wrote:<snip>
Since you've already been shown the super easy way, I'll dare to be a little different:
#!/usr/bin/perl
use strict; use warnings;
$/ = ''; # enter "paragraph" mode while (<>) { # call with: perl script_name file1 my %contact = map { /^(\w+):\s*(.+)$/ } split /\n/, $_; print "$_: $contact{$_}\n" foreach qw(Name City State); print "\n" }
__END__
The first way your were shown is probably a little easier, but this
method is probably better if you want to do anything more complicated
than simple printing, since you have the whole hash to play with. It's
a different way of thinking about the problem at least.
Thanks for posting this. My first thought was a hash, thinking in terms
of key-item but I couldn't figure out how to populate the hash. This
code will give me something to analyze. The "map" function looks like
voodoo to me:)
It's not so scary, let's look at it in a longer form:
my %contact; # create the hash to populate my @lines = split /\n/, $_; # break paragraph into lines for my $line (@lines) { # walk the lines from the paragraph we read if ($line =~ /^(\w+):\s*(.+)$/) { # find hash key and value $contact{$1} = $2; # assign to hash } }
I was just lazy and didn't want to type that much, so I cheated:
# read the following comments from the bottom up
my %contact = # stick all that here, assumes Key, Value, Key, Value...
map { /^(\w+):\s*(.+)$/ } # match each line and return what we capture in parens
split /\n/, $_; # break paragraph into lines and hand them all to map
If you want more info, try:
perldoc -f split perldoc -f map
Hope that clears it up a little.
James
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>