[prev in list] [next in list] [prev in thread] [next in thread]
List: perl-beginners
Subject: Re: compare and replace each line with Hash
From: Jim Gibson <jimsgibson () gmail ! com>
Date: 2012-11-18 20:59:15
Message-ID: 072C7EFA-539A-4036-BAD2-6481935A70FA () gmail ! com
[Download RAW message or body]
On Nov 15, 2012, at 7:30 PM, Mohan L wrote:
> Dear All,
>
> The below is my input data:
>
> $ cat demo.txt
> 159350,PP02,Backup,0,Done
> 159349,B02_bkp,Backup,0,Done
> 159347,B02_bkp,Backup,0,Done
> 159346,B02_bkp,Backup,0,Done
> 159345,B02_bkp,Backup,0,Not
> 159344,02_bkp,Backup,0,Done
>
> I am using Text::CSV_XS to read the above comma separated file. Here is the
> code I am using the above file line by line.
>
> #!/usr/bin/perl
> use strict;
> use warnings;
> use Data::Dumper;
> use Text::CSV_XS;
>
>
> my $file="/data/demo.txt";
> if(defined $ARGV[0])
> {
> $file=$ARGV[0];
> }
>
> my $csv = Text::CSV_XS->new({binary => 1,sep_char => ','}) or die "Cannot
> use CSV: ".Text::CSV->error_diag ();
> open(my $data, '<', $file) or die "Could not open '$file'\n";
> while (my $line = <$data>)
> {
> if ($csv->parse($line))
> {
> my @row = $csv->fields();
> print "$row\n";
> // compare and replace string name to id.
> }
> else
> {
> warn "Line could not be parsed: $line\n";
> }
> }
>
> I have two hash reference like :
>
> $VAR1 = \{
> '1' => {
> 'name' => 'Backup',
> 'id' => '1'
> },
> '2' => {
> 'name' => 'Catalog',
> 'id' => '2'
> }
> };
>
>
> $VAR2 = \{
> '1' => {
> 'name' => 'Done',
> 'id' => '1'
> },
> '2' => {
> 'name' => 'Not',
> 'id' => '2'
> }
> };
>
>
>
> I want to compare $row[2] and $row[4] with the above hash and want to
> replace string name to respective id. for example:
>
>
> 159350,PP02,1,0,1
> 159349,B02_bkp,1,0,1
> 159347,B02_bkp,1,0,1
> 159346,B02_bkp,1,0,1
> 159345,B02_bkp,1,0,2
> 159344,02_bkp,1,0,1
The first thing to do is create a hash that has the replacements you want to apply. \
Assuming that you want to apply the same replacements to columns 3 and 5, the hash \
would look like this:
my %replace = (
Backup => 1,
Catalog => 2,
Done => 1,
Not => 2,
);
You can get that from your two hashes by suitable extractions.
Then you can split your input lines on commas and apply the following operation to \
columns 3 and 5. For example, for column 3:
if( exists $replace{$row[2]} ) {
$row[2] = $replace{$row[2];
}
If your replacements are different for the two columns, then you will have to use two \
hashes.
You can shorten the above to:
$row[2] = exists $replace{$row[2]} ? $replace{$row[2]} : $row[2];
or, for later Perls:
$row[2] = $replace{$row[2]} // $row[2];
--
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic