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

How if I want to replace for example abcd| a a7- into [a] [a7] [a] in perl?

Replies are listed 'Best First'.
Re: replace character to bracket in perl
by kennethk (Abbot) on Apr 04, 2016 at 14:41 UTC
    As GotToBTru says, the process for mapping your input string to your output string is not clear. See How do I post a question effectively?. Can you wrap your input and output strings in <code> tags and describe in English or pseudocode the steps to go from abcd| a a7- to [a] [a7] [a], or however that is supposed to be?

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: replace character to bracket in perl
by GotToBTru (Prior) on Apr 04, 2016 at 14:34 UTC

    Starting from "abcd| a a7-", you want to get "[a] [a7] [a]". I see 3 a's in the input, and 3 in the output, but I'm not sure what goes where. Except maybe the a7.

    Can you be more clear? What have you got so far?

    But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

Re: replace character to bracket in perl
by AnomalousMonk (Archbishop) on Apr 04, 2016 at 17:45 UTC
Re: replace character to bracket in perl
by ww (Archbishop) on Apr 04, 2016 at 21:12 UTC

    I'd hoped OP would correct or clarify the (possible disparity?) between the order of the inputs and the order of the outputs in the original post -- but given the time that's passed since the replies above encouraged her to do so, here's one approach (with enough bad ideas such as some tender regexen and making all variables global that you should NOT cargo cult it; turn it in for homework; or use in any production environment):

    #!/usr/bin/perl -w use strict; #1159495 my $input = 'abcd| a a7-'; my ( $item, @display, $display, $out, ); my @deSpaced = split / /, $input; for $item(@deSpaced) { if ($item =~ /(a).*\|/ ) { # match first part of $input? $out = '[' . $1 . ']'; push @display, $out; } if ( $item =~ /(^a$)/ ) { # match middle of $input? $out = '[' . $1 . ']'; push @display, $out; } elsif ( $item =~ /(a[0-9]{1}).+/ ) { # match last part of $i +nput? $out = '[' . $1 . ']'; push @display, $out; } } foreach my $saved(@display) { print $saved . ' '; } =head EXECUTION: C:\ PMonks\1159495.pl [a] [a] [a7] C:\ =cut

    The code ignores ("leaves as an exercise for the Seeker") the re-ordering expressed in OP's desire to transform
    "abcd| a a7-" into "a a7 a"
    The last element with an "a" in the original is "a7" (ignoring the hyphen) But your output makes the bracketed "a7" appear before a final (bracketed) "a."


    Looks like a gimmé request!
    Sorry, we expect SOPW to seek wisdom, not to ask us to do so for them.