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.


In reply to Re: replace character to bracket in perl by ww
in thread replace character to bracket in perl by Allegra

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.