benaw has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I am trying to substitute the second pipe in a string I am looping through a text file by using

open (MYFILE, $RD); while (<MYFILE>) { print $_ } close (MYFILE);

in the file there are lines like

Name and Number:|47355|Multipurpose Room - General Scheme:|SCHEME 5.1|Water Room Title:|ELEC RM|Engineering|LEVEL 4

I would like the output to remove the second pipe on the lines with name and number and scheme (and for the line Room title I'm either going to delete whats after the second pipe or try and turn them into new lines for department and Level)

So it would look like:

Name and Number:|47355 Multipurpose Room - General Scheme:|SCHEME 5.1 Water Room Title:|ELEC RM Department:Engineering Level:LEVEL 4

not sure if i'll do the second bit with the room title it might start getting a bit complex

what I'm asking is how do I match m/Scheme:/ and substitute in that line the second pipe with a blank space note anything could come after the first pipe and i want to maintain that data?

Replies are listed 'Best First'.
Re: Replacing second occurrence of a character
by BrowserUk (Patriarch) on Jan 07, 2016 at 07:07 UTC

    #! perl -slw use strict; while( <DATA> ) { m[^(.+)\|(.+)\|([^\|\n]+)(\|.+)?$]; if( $1 eq 'Name and Number:' or $1 eq 'Scheme:' ) { print "$1|$2 $3"; } else { print "$1\nDepartment:$2\nLevel:$3"; } } __DATA__ Name and Number:|47355|Multipurpose Room - General Scheme:|SCHEME 5.1|Water Room Title:|ELEC RM|Engineering|LEVEL 4
    C:\test>1152142 Name and Number:|47355 Multipurpose Room - General Scheme:|SCHEME 5.1 Water Room Title:|ELEC RM Department:Engineering Level:LEVEL 4

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Replacing second occurrence of a character
by hdb (Monsignor) on Jan 07, 2016 at 08:52 UTC

    For your application I would prefer split. For one, it does remove all pipes, and secondly, you get all your bits as separate items for further processing. For example, your data "Name and Number" really looks more like "Number and Name", so if you split it you could change the order.

    use strict; use warnings; while(<DATA>){ chomp; my( $type, @data ) = split /[|]/; if( $type eq 'Room Title:' ) { print "\n$type $data[0]\n"; print "Department: $data[1]\n"; print "Level: $data[2]\n"; } else { print "$type @data\n"; } } __DATA__ Name and Number:|47355|Multipurpose Room - General Scheme:|SCHEME 5.1|Water Room Title:|ELEC RM|Engineering|LEVEL 4