|
|
|
|
|
|
#1
|
||||
|
||||
|
Perl Programming Question.
Anyone here good with Perl?
Here's the question: I have a field that is read from a flat file and assigned a $name in some code. So, let's say the flat file looks like this: Monkey_Brains|1.00|Brown Naturally, the first field is "Monkey_Brains" The second field is "1.00" The third field is "Brown" The first field is assigned a variable, we'll call it: $name Now here's what I would like to do. All the fields in the $name spot have an underscore '_' between each word. I would like code that could read this field and strip the underscore out. So "Monkey_Brains" would be come "Monkey Brains" In essence: $name would equal "Monkey_Brains" Then some code that reads and modifies $name $modifiedname would now equal "Monkey Brains" Many Thanks, Pete |
|
#2
|
||||
|
||||
|
I don't know PERL syntax but the gist is to read the name field into a string variable, I gues that is what $name is. Then do a search for the underscore. I assume there is some string function that will return the position of any underscore found in the string. When you know the position, you can use it to replace the character at that position with a blank.
__________________
MB-less |
|
#3
|
|||
|
|||
|
My perl is a bit rusty, but I think this is what you need:
$name =~ s/\_/ /; This just substitutes the space for all underscores.
__________________
as ever Paul 1989 560SL 1987 300SDL 1987 300TD 1983 BMW 633CSi 1972 280SE 4.5 |
|
#4
|
|||
|
|||
|
Quote:
This will globally substitute all '_' to ' ' (space). Kachun
__________________
Kachun 1990 300SE 2003 E320 |
|
#5
|
||||
|
||||
|
My brother uses perl for everything. I asked him about it :
Say file.txt has the following contents: Monkey_Brains|1.00|Brown Monkey_Brains|1.00|Brown Monkey_Brains|1.00|Brown Monkey_Brains|1.00|Brown Monkey_Brains|1.00|Brown parse.pl #!/usr/bin/perl -w use strict; while(<>) { chomp($_); my ($name, $number, $colour) = split(/\|/); $name =~ s/_/ /g; print "$name, $number, $colour\n"; } command line: perl parse.pl < file.txt output = Monkey Brains, 1.00, Brown Monkey Brains, 1.00, Brown Monkey Brains, 1.00, Brown Monkey Brains, 1.00, Brown Monkey Brains, 1.00, Brown
__________________
Chris Muc '08 R320CDI 265,000km '15 GL350 206,000km "You can fight without ever winning But never ever win without a fight" Neil Peart |
|
#6
|
|||
|
|||
|
I had to open up this thread to satisfy an idle curiosity...
Yep, perl is just as ugly as I remember. Ugly, ugly, ugly langauge. Please take it out back behind the barn and put it out of its misery. |
![]() |
| Bookmarks |
|
|