pearllearner315 has asked for the wisdom of the Perl Monks concerning the following question:
What I would like to do is, loop through this text file line by line and extract whatever comes after "TG:" and store as a key to a hash, and extract whatever comes after "type:" and store as a value to the key that was just stored. This is what I have so far:(Special) TG: VIN:1000000 type: a very special type of plane (Special) TG: VIN:1000001 type: a very special type of car (Special) TG: VIN:1000002 type: a very special type of boat this repeats many times..
I then print the hash but I only get the first entry in the hash, as if the loop stopped after the first iteration. What could be the problem here? Is it the regex? Thank you in advance for your wisdom!!#!/usr/bin/perl use strict; use warnings; my $textfile = 'file.txt'; open(TEXT, '<', $textfile) or die $!; my %hash; local $/="(Special)"; while(<TEXT>){ if ($_ =~ /TG:\s(VIN:\d+)\ntype:\s(.+)\n/){ my $keys = $1; my $values = $2; $hash{$keys} = $values; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: extracting strings from text file
by LanX (Saint) on Sep 08, 2018 at 23:42 UTC | |
|
Re: extracting strings from text file
by AnomalousMonk (Archbishop) on Sep 09, 2018 at 01:15 UTC | |
|
Re: extracting strings from text file
by tybalt89 (Monsignor) on Sep 09, 2018 at 14:43 UTC | |
by GrandFather (Saint) on Sep 09, 2018 at 21:18 UTC |