Well, the regex and split will certainly work. I'd like to provide two more options for you.

The first uses index and substr. This has the advantage of being very fast (often faster than regex -- regexes can do more, though). I don't know if it's faster than split (probably not), but there may be reasons for you to use it.

my $string = '(<some word> | No Qualifier | <some word> | <some word>' +; my $start = index( $string, '|' ); # find first pipe position my $end = index( $string, '|', $start+1 ); # find next pipe position my $qualifier = substr( $string, $start, $end-$start+1 ); # extract

The second suggestion I have is a bit more robust, and leverages the module Text::CSV_XS. You'd use this approach if you have, e.g. a file of lines that look like your example -- and especially if you're interested in more than one field in that line, and/or if your data might have escaped pipes in it.

use IO::File; use Text::CSV_XS; my $csv = Text::CSV_XS->new({ sep_char=>'|' }); my $io = IO::File->new('myfile.piped.txt', '<') or die "Can't read fi +le: $!\n"; until ($io->eof) { my $row = $csv->getline($io); # read and parse line into an ARRAY +ref print "Second field says: ", $row->[1], "\n"; }

Even if your data isn't in a file, Text::CSV_XS can parse it for you; it's worth looking into.

<radiant.matrix>
Ramblings and references
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

In reply to Re: Str extract the word between the first and the 2nd '|' character by radiantmatrix
in thread Str extract the word between the first and the 2nd '|' character by dani_cv

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.