On Thu, Jan 15, 2004 at 08:38:11AM -0600, James Edward Gray II ([EMAIL PROTECTED]) wrote: > On Jan 14, 2004, at 10:28 PM, Kenton Brede wrote: > > >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 > } > } > <snip>
Thanks for the great explanation. I've been working with the code above since I need more hash practice, trying to keep on track with the original poster's question. The code below works fine except I can't figure out how to put one "\n" between the two records like - Name: Bob City: Austin State: Texas Name: Jose City: Denver State: Colorado If I place "print "\n";" after the print line I get double spaces between all lines. If I place it outside the last "for" loop I get double spaces between the two records. What I have below just prints them in one block. Hope that all made some sense:) Thanks for any help, Kent #!/usr/bin/perl use warnings; use strict; while (<DATA>) { my @lines = (split /\n/, $_); my %contact; for my $line (@lines) { if ($line =~ /^(\w+):\s*(.+)$/) { $contact{$1} = $2; for (keys %contact) { if (/^Name/ or /^City/ or /^State/) { print "$_: $contact{$_}\n"; } } } } } __DATA__ Name: Bob City: Austin State: Texas Address: 123 Whatever Age: 46 Name: Jose City: Denver State: Colorado Address: 118 Mystreet Age: 28 __END__ -- "I am always doing that which I can not do, in order that I may learn how to do it." --Pablo Picasso -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>