0

I have a function that takes in filename and prints the content of the file

#test.pl
while (<>) {
    print $_;
}
exit(0);

I want to run this on the command line except instead of a filename I want to use the actual content as parameter without changing the script, similarly to an anonymous FIFO (e.g. "<(...)" operator in shell) to substitute a filename string with it's content?

2
  • 2
    It's not clear what you are asking. <> can already read from stdin (btw, you should be using <<>>). What do you mean when you say "I have a function" ? Commented Apr 17, 2019 at 1:51
  • 2
    If you provide a filename of '-' then perl will interpret that as "read from STDIN", however that's also the default behaviour if you don't supply a filename at all. In the bash shell you can do something like this: test.pl <<<"some content here which bash will supply on STDIN" Commented Apr 17, 2019 at 4:10

1 Answer 1

2

This is a shell question, but you didn't specify which shell.

sh

It's simplest to simply pass the data to STDIN instead.

printf 'foo bar' | test.pl

printf 'foo\nbar\n' | test.pl

test.pl <<'.'
foo
bar
.

bash

In addition to the solutions for sh, you can also use the following:

test.pl <<<'foo bar'

test.pl <<<$'foo\nbar\n'

test.pl <( printf 'foo\nbar\n' )

The last one avoids using STDIN. This is (internally) more complicated than the other solutions, but it allows you to pass multiple "virtual files".

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you that worked. However this solution does not work when there are multiple arguments to the script. Is it possible to pass the data to STDIN for only the last param?
As the answer mentions, the last one does.
I apologize so for the final example if I want to use multiple args I would just do test.pl ARG1 <( printf 'foo\nbar\n' ) where <( printf 'foo\nbar\n' ) is ARG2?
Yes. For the others solutions, you can only do that if the other args are options (test.pl --foo=bar <<<'foo bar' is ok, but test.pl' file.txt file2.txt <<<'foo bar' is not ok)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.