Search code examples
perlsubstr

perl --> printing characters in between the multiple metacharacters present in a single line


I am trying a script to find out the characters between the metacharacter "|". I tried to get the position of the first and the succeeding "|" metacharacter and tried to print the string between those two positions. Below is the code I tried:

File : | A| B| Count| D| E|

Expected output : A B Count D E

if($line =~ /\|/) 
{
while ($line =~ m/\|/g) 
{
my $start_pos = $-[0]; 
my $end_pos = $+[0]; 
my $hit_pos = "$start_pos - $end_pos";
my $char = substr($line, $start_pos, $end_pos);
if($char =~/\w/){
  print "$char\n";
}
}
}

Solution

  • Using split:

    my $line = '| A| B| Count| D| E|';
    
    my @fields = split(/\|/, $line, -1);
    shift(@fields);  # Ignore stuff before first "|"
    pop(@fields);    # Ignore stuff after last "|"
    
    say "<$_>" for @fields;
    

    Output:

    < A>
    < B>
    < Count>
    < D>
    < E>
    

    Using a regex match:

    my $line = '| A| B| Count| D| E|';
    
    my @fields = $line =~ / \| ([^|]*) (?=\|) /xg;
    
    say "<$_>" for @fields;
    

    Output:

    < A>
    < B>
    < Count>
    < D>
    < E>
    

    Using a regex match (alternative):

    my $line = '| A| B| Count| D| E|';
    
    while ($line =~ / \| ([^|]*) (?=\|) /xg) {
       say "<$1>";
    }
    

    Output:

    < A>
    < B>
    < Count>
    < D>
    < E>