0

I am brand new to Perl and struggling with it.

I need to learn just the basics and not much.

I googled and got no simple answer to my question.

I have a string which contains numbers, dots, dashes, colon: and two alphabets.

I want to replace one alphabet by a space and the other by nothing.

How do I do this?

Is there no string.ReplaceChar(theChar, replacement)?

Borodin
  • 126,100
  • 9
  • 70
  • 144
big_space
  • 71
  • 2
  • 10
  • 2
    What do you mean by 'two alphabets'? Does your data have a-z twice, in which case upper/lower/mixed? Or do you mean two character sets? – TaninDirect Nov 26 '14 at 01:41
  • possible duplicate of [perl find and replace ../ and  ](http://stackoverflow.com/questions/12291901/perl-find-and-replace-and-160) – Manu Mathew Nov 26 '14 at 08:52
  • @TaninDirect - Thanks for the question. It has only two alphabets each occurring only once and no more. – big_space Nov 26 '14 at 19:03

2 Answers2

1

You can try as in the example below:

From commandline:

To replace only the first occurrence of the alphabets:

sdlcb@ubuntu:~$ echo "123.-A456:7B9AB0" | perl -pe 's/A//; s/B/ /'
123.-456:7 9AB0

To replace all occurrences of the alphabets:

sdlcb@ubuntu:~$ echo "123.-A456:7B9AB0" | perl -pe 's/A//g; s/B/ /g'
123.-456:7 9 0

Within script:

#!/usr/bin/perl -w
use strict;

my $data = "123.-A456:7B9AB0";
my $final_data = $data;

$final_data =~ s/A// ;
$final_data =~ s/B/ /;

print "data: $data\n";
print "final_data: $final_data\n";

Use g for substituting all occurrences.

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
  • I am making another question related to this. I was trying to convert your code to a sub routine. It failed. I can't post the question right now because of the 90 mins time limit. Please help me if possible. Will add the link here soon. – big_space Nov 26 '14 at 20:13
  • AMD - The new question is here - http://stackoverflow.com/questions/27158608/follow-up-post-unable-to-make-a-simple-subroutine-to-clean-a-string – big_space Nov 26 '14 at 20:48
0

Perl lends itself to using regular expressions, so that is how I would approach it;

#!/usr/bin/perl -w
use strict;

my $ALPHABET = 'abcde';
my $source_data = "1.2.3-$ALPHABET:$ALPHABET";

my $dest_data = $source_data
$dest_data =~ s/(-)$ALPHABET(:)/$1 $2/;

print "source_data: $source_data\n";
print "dest_data: $dest_data\n";

--->
source_data: 1.2.3-abcde:abcde
dest_data: 1.2.3- :abcde

Here the reqular expresion operator (=~) is substituting the first occurance of the pattern (-)$ALPHABET(:) with a '- :' string.

This pattern is using capture groups '()' to locate the match within the data. Depending on your data you will likely need to adjust the patterns in the capture groups.

The backrefernces $1 and $2 within the match are used for demonstration purposes.

We could help with a more specific regex if you include example data in your question.

TaninDirect
  • 458
  • 1
  • 7
  • 15