CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions: Re: [Giffredo] Split table,Count and substitution character: Edit Log



Chris Charley
User

Mar 23, 2014, 2:23 PM


Views: 16225
Re: [Giffredo] Split table,Count and substitution character

Hello Giffredo,

I will try to walk through FishMonger's code.


Code
use Text::CSV_XS; 

my $csv = Text::CSV_XS->new({ binary => 1, sep_char => ' ', eol => "\n" });


Uses the module Text::CSV_XS and he creates a Text::CSV_XS object in the code to parse and print the input line. Text::CSV splits the line on a single space for input, (sep_char => ' '), and also uses a space to separate the columns for output, print.


Code
while (my $line = $csv->getline(*DATA))

Here the program reads a line (from the *DATA filehandle - your program would use a filehandle for your input file instead).


Code
$cnt{'.'}  = $line->[4] =~ tr/././;  
$cnt{','} = $line->[4] =~ tr/,/,/;


This code uses the transliteration (tr) operator to count the periods and commas in the column noted as $line->[4]. These counts are assigned to %cnt hash which stores the counts.


Code
$line->[5] = $cnt{'.'} . $cnt{','};


This sets array item 6, (arrays count starting with 0).


Code
$csv->print(*STDOUT, $line);


This code uses the Text::CSV object to print (to the screen). To print to an output file instead, you would replace *STDOUT with your output filehandle.

This code gives the results:

Code
chrM 136 A 6 ,,.......,, 74  
chrM 137 A 6 ,,,,,,.. 26
chrM 138 A 6 ,,..,,,, 26
chrM 139 C 6 ,,,..,,, 26
chrM 140 C 6 ..,,, 23
chrM 141 C 6 ,,,,,, 06
chrM 142 T 6 ,,,,,, 06


To get your desired output, the code would need 1 or 2 minor changes.

Change

Code
$line->[5] = $cnt{'.'} . $cnt{','};

To

Code
splice @$line, 4, 2, "$cnt{'.'}:$cnt{','}";



(This post was edited by Chris Charley on Mar 23, 2014, 4:02 PM)


Edit Log:
Post edited by Chris Charley (User) on Mar 23, 2014, 2:28 PM
Post edited by Chris Charley (User) on Mar 23, 2014, 2:29 PM
Post edited by Chris Charley (User) on Mar 23, 2014, 3:30 PM
Post edited by Chris Charley (User) on Mar 23, 2014, 4:02 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives