How to selectively suppress perl output?

The following perl statement in a bash script consists of two substatements. I intend the first perl substatement (the assignment with glob) to get input from the preceding bash pipe, and the second perl substatement (the foreach loop) to output back to bash. However, the first perl substatement undesirably outputs back to bash in addition to the desirable output from the second perl substatement. I want only the second perl substatement to output back to bash. Please show me how to prevent the first perl substatement from outputting to bash.

#!/bin/bash
set -f
vLn='bb cc dd'
echo $vLn | \
perl -pe 'my @vAry = glob; foreach my $i (@vAry) {print "$i\n";}'

The perl statement consists of
my @vAry = glob
and
foreach my $i (@vAry) {print "$i\n";}

The output from the first perl substatement is
bb cc dd

The output from the second perl substatement is
bb
cc
dd

I would like the entire perl statement to output the following.
bb
cc
dd

However, the actual output from the entire perl statement is
bb
cc
dd
bb cc dd

How can one suppress the output from the first perl substatement?

Many thanks in advance.

Update:

This question has been successfully answered by Post#8 by durden_tyler.

If you're trying to print those three words vertically, you may try this:

$ x='bb cc dd'
$ echo $x | sed "s/ /\n/g"
bb
cc
dd

That is not what I want. I need perl definitely. I need communication between bash and perl.

#! /bin/bash
x='bb cc dd'
echo $x | perl -le '@x=split/\s+/,<>; print for (@x)'
$ echo  $x | perl -lane '$_=~s/ /\n/g;print $_'
bb
cc
dd

@itkamaraj: If -a switch is used, we could also do this:

echo  $x | perl -lane 'print for (@F)'
1 Like

Do not remove "glob", please!

Are you okay with removing the "p" switch?
It's similar to the "n" switch, but it prints the input line by default (similar in function to the "p" switch of sed).

For example, if your shell script were like so -

$
$
$ cat -n bash_to_perl.sh
     1  #!/bin/bash
     2  set -f
     3  vLn='bb cc dd'
     4  echo $vLn | \
     5  perl -pe ''
$
$

then the output will be the value of $vLn, even when you are doing nothing in your Perl one-liner -

$
$ cat -n bash_to_perl.sh
     1  #!/bin/bash
     2  set -f
     3  vLn='bb cc dd'
     4  echo $vLn | \
     5  perl -pe ''
$
$
$ ./bash_to_perl.sh
bb cc dd
$
$

If you use the "n" switch instead, then -

$
$
$ cat -n bash_to_perl.sh
     1  #!/bin/bash
     2  set -f
     3  vLn='bb cc dd'
     4  echo $vLn | \
     5  perl -ne 'my @vAry = glob; foreach my $i (@vAry) {print "$i\n";}'
$
$
$ ./bash_to_perl.sh
bb
cc
dd
$
$

tyler_durden

1 Like