can a perl script be written to receive data from any of (1) file, (2) stdin, (3) redirect?How can I redirect and append both stdout and stderr to a file with Bash?How can I run a shell script on a remote machine with a local Perl program?redirect COPY of stdout to log file from within bash script itselfIs There Any Way to Pipe Data from Perl to a Unix Command Line UtilityHow to flush I/O buffer in coprocess's pipeHow can I enable/disable print output for a given perl script?How to use the Unix/AIX find command with a pipe in Perl?Is it possible to pipe input to another script with '<' using the system() in perl?Redirect child process stdin only and drop data from stdout and stderrUNIX C programming input re-direction command

Pythagorean triple with hypotenuse a power of 2

Almost uniform convergence implies convergence in measure

Why does The Ancient One think differently about Doctor Strange in Endgame than the film Doctor Strange?

Round towards zero

Why in most German places is the church the tallest building?

How do I get toddlers to stop asking for food every hour?

LeetCode: Group Anagrams C#

Did the British navy fail to take into account the ballistics correction due to Coriolis force during WW1 Falkland Islands battle?

Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?

What is the difference between "Grippe" and "Männergrippe"?

Immutable builder and updater

Is a player able to change alignment midway through an adventure?

How to respectfully refuse to assist co-workers with IT issues?

Is for(( ... )) ... ; a valid shell syntax? In which shells?

What is this symbol: semicircles facing each other?

Is there any music source code for sound chips?

Why are non-collision-resistant hash functions considered insecure for signing self-generated information

An interview question: What's the number of String objects being created?

Do they have Supervillain(s)?

Remarkable applications of Dickson's lemma

How much authority do teachers get from *In Loco Parentis*?

How can I unambiguously ask for a new user's "Display Name"?

Can a Rogue PC teach an NPC to perform Sneak Attack?

Algorithms vs LP or MIP



can a perl script be written to receive data from any of (1) file, (2) stdin, (3) redirect?


How can I redirect and append both stdout and stderr to a file with Bash?How can I run a shell script on a remote machine with a local Perl program?redirect COPY of stdout to log file from within bash script itselfIs There Any Way to Pipe Data from Perl to a Unix Command Line UtilityHow to flush I/O buffer in coprocess's pipeHow can I enable/disable print output for a given perl script?How to use the Unix/AIX find command with a pipe in Perl?Is it possible to pipe input to another script with '<' using the system() in perl?Redirect child process stdin only and drop data from stdout and stderrUNIX C programming input re-direction command






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















Several unix utilities, such as fmt, head, and cat, can receive data in any of 3 ways: a filename; a pipe from standard input; or a redirect "<". For instance:



printf '%b' 'dog ncat nratn' > dogcatrat
fmt dogcatrat
cat dogcatrat | fmt
fmt < dogcatrat


Can one write a perl script that will behave with the same versatility? Or is there a good reason not to attempt this? And is "pipe from standard input" the right way to refer to the line of code that starts with cat?



I want to write myfmt.pl, to be used in any of these three ways.










share|improve this question
























  • uh, yes? If you have an argument, read from that file, otherwise read from stdin.

    – Tanktalus
    Mar 27 at 17:40











  • Yes, this is exactly the use case that the special filehandle ARGV addresses.

    – mob
    Mar 27 at 17:58






  • 1





    Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

    – ikegami
    Mar 27 at 18:36


















1















Several unix utilities, such as fmt, head, and cat, can receive data in any of 3 ways: a filename; a pipe from standard input; or a redirect "<". For instance:



printf '%b' 'dog ncat nratn' > dogcatrat
fmt dogcatrat
cat dogcatrat | fmt
fmt < dogcatrat


Can one write a perl script that will behave with the same versatility? Or is there a good reason not to attempt this? And is "pipe from standard input" the right way to refer to the line of code that starts with cat?



I want to write myfmt.pl, to be used in any of these three ways.










share|improve this question
























  • uh, yes? If you have an argument, read from that file, otherwise read from stdin.

    – Tanktalus
    Mar 27 at 17:40











  • Yes, this is exactly the use case that the special filehandle ARGV addresses.

    – mob
    Mar 27 at 17:58






  • 1





    Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

    – ikegami
    Mar 27 at 18:36














1












1








1








Several unix utilities, such as fmt, head, and cat, can receive data in any of 3 ways: a filename; a pipe from standard input; or a redirect "<". For instance:



printf '%b' 'dog ncat nratn' > dogcatrat
fmt dogcatrat
cat dogcatrat | fmt
fmt < dogcatrat


Can one write a perl script that will behave with the same versatility? Or is there a good reason not to attempt this? And is "pipe from standard input" the right way to refer to the line of code that starts with cat?



I want to write myfmt.pl, to be used in any of these three ways.










share|improve this question














Several unix utilities, such as fmt, head, and cat, can receive data in any of 3 ways: a filename; a pipe from standard input; or a redirect "<". For instance:



printf '%b' 'dog ncat nratn' > dogcatrat
fmt dogcatrat
cat dogcatrat | fmt
fmt < dogcatrat


Can one write a perl script that will behave with the same versatility? Or is there a good reason not to attempt this? And is "pipe from standard input" the right way to refer to the line of code that starts with cat?



I want to write myfmt.pl, to be used in any of these three ways.







perl redirect pipe filenames






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 17:34









Jacob WegelinJacob Wegelin

914 bronze badges




914 bronze badges















  • uh, yes? If you have an argument, read from that file, otherwise read from stdin.

    – Tanktalus
    Mar 27 at 17:40











  • Yes, this is exactly the use case that the special filehandle ARGV addresses.

    – mob
    Mar 27 at 17:58






  • 1





    Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

    – ikegami
    Mar 27 at 18:36


















  • uh, yes? If you have an argument, read from that file, otherwise read from stdin.

    – Tanktalus
    Mar 27 at 17:40











  • Yes, this is exactly the use case that the special filehandle ARGV addresses.

    – mob
    Mar 27 at 17:58






  • 1





    Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

    – ikegami
    Mar 27 at 18:36

















uh, yes? If you have an argument, read from that file, otherwise read from stdin.

– Tanktalus
Mar 27 at 17:40





uh, yes? If you have an argument, read from that file, otherwise read from stdin.

– Tanktalus
Mar 27 at 17:40













Yes, this is exactly the use case that the special filehandle ARGV addresses.

– mob
Mar 27 at 17:58





Yes, this is exactly the use case that the special filehandle ARGV addresses.

– mob
Mar 27 at 17:58




1




1





Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

– ikegami
Mar 27 at 18:36






Nit: cat dogcatrat | fmt and fmt < dogcatrat both feed fmt's STDIN. There's no difference between the two as far as fmt is concerned.

– ikegami
Mar 27 at 18:36













2 Answers
2






active

oldest

votes


















5















The ARGV special filehandle will do this by default. It is also the handle used by readline (aka the <> and <<>> operators) when not given a handle. So this is actually pretty common in Perl scripts.



#!/usr/bin/env perl
use 5.022;
use warnings;
while (my $line = <<>>)
# $line from one of the filenames passed as an argument, otherwise STDIN
# $ARGV is the current filename, or - when reading from STDIN



You can use the <> operator instead to support older versions of Perl, but the <<>> operator added in Perl 5.22 is a better option for this task if available, because the standard <> operator allows passing strange things like date| to run processes rather than read files.



For safer filename-only operation while supporting older versions of Perl, you could use ARGV::readonly or emulate the <<>> operator like the following:



#!/usr/bin/env perl
use strict;
use warnings;
unshift @ARGV, '-' unless @ARGV;
while (my $file = shift)
my $fh;
if ($file eq '-')
$fh = *STDIN;
else
open $fh, '<', $file or die "open $file failed: $!";

while (my $line = <$fh>)
# ...




(Technically the <<>> operator also does not allow passing - as an argument to read STDIN, but it is your choice if you want to allow that.)






share|improve this answer



























  • It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

    – ikegami
    Mar 27 at 18:37











  • What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

    – ikegami
    Mar 27 at 18:39



















1















It appears that the following script fills the bill.



#!/usr/bin/perl
use strict;
use warnings;
use 5.18.2;
local $/ = ""; # input record separator: one paragraph at a time
while (<>)
print;
print "n";
say '-' x 30;



Example:



printf '%b' 'dog ncat nratn' > aaa
try.pl aaa
cat aaa | try.pl
try.pl < aaa





share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383363%2fcan-a-perl-script-be-written-to-receive-data-from-any-of-1-file-2-stdin-3%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5















    The ARGV special filehandle will do this by default. It is also the handle used by readline (aka the <> and <<>> operators) when not given a handle. So this is actually pretty common in Perl scripts.



    #!/usr/bin/env perl
    use 5.022;
    use warnings;
    while (my $line = <<>>)
    # $line from one of the filenames passed as an argument, otherwise STDIN
    # $ARGV is the current filename, or - when reading from STDIN



    You can use the <> operator instead to support older versions of Perl, but the <<>> operator added in Perl 5.22 is a better option for this task if available, because the standard <> operator allows passing strange things like date| to run processes rather than read files.



    For safer filename-only operation while supporting older versions of Perl, you could use ARGV::readonly or emulate the <<>> operator like the following:



    #!/usr/bin/env perl
    use strict;
    use warnings;
    unshift @ARGV, '-' unless @ARGV;
    while (my $file = shift)
    my $fh;
    if ($file eq '-')
    $fh = *STDIN;
    else
    open $fh, '<', $file or die "open $file failed: $!";

    while (my $line = <$fh>)
    # ...




    (Technically the <<>> operator also does not allow passing - as an argument to read STDIN, but it is your choice if you want to allow that.)






    share|improve this answer



























    • It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

      – ikegami
      Mar 27 at 18:37











    • What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

      – ikegami
      Mar 27 at 18:39
















    5















    The ARGV special filehandle will do this by default. It is also the handle used by readline (aka the <> and <<>> operators) when not given a handle. So this is actually pretty common in Perl scripts.



    #!/usr/bin/env perl
    use 5.022;
    use warnings;
    while (my $line = <<>>)
    # $line from one of the filenames passed as an argument, otherwise STDIN
    # $ARGV is the current filename, or - when reading from STDIN



    You can use the <> operator instead to support older versions of Perl, but the <<>> operator added in Perl 5.22 is a better option for this task if available, because the standard <> operator allows passing strange things like date| to run processes rather than read files.



    For safer filename-only operation while supporting older versions of Perl, you could use ARGV::readonly or emulate the <<>> operator like the following:



    #!/usr/bin/env perl
    use strict;
    use warnings;
    unshift @ARGV, '-' unless @ARGV;
    while (my $file = shift)
    my $fh;
    if ($file eq '-')
    $fh = *STDIN;
    else
    open $fh, '<', $file or die "open $file failed: $!";

    while (my $line = <$fh>)
    # ...




    (Technically the <<>> operator also does not allow passing - as an argument to read STDIN, but it is your choice if you want to allow that.)






    share|improve this answer



























    • It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

      – ikegami
      Mar 27 at 18:37











    • What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

      – ikegami
      Mar 27 at 18:39














    5














    5










    5









    The ARGV special filehandle will do this by default. It is also the handle used by readline (aka the <> and <<>> operators) when not given a handle. So this is actually pretty common in Perl scripts.



    #!/usr/bin/env perl
    use 5.022;
    use warnings;
    while (my $line = <<>>)
    # $line from one of the filenames passed as an argument, otherwise STDIN
    # $ARGV is the current filename, or - when reading from STDIN



    You can use the <> operator instead to support older versions of Perl, but the <<>> operator added in Perl 5.22 is a better option for this task if available, because the standard <> operator allows passing strange things like date| to run processes rather than read files.



    For safer filename-only operation while supporting older versions of Perl, you could use ARGV::readonly or emulate the <<>> operator like the following:



    #!/usr/bin/env perl
    use strict;
    use warnings;
    unshift @ARGV, '-' unless @ARGV;
    while (my $file = shift)
    my $fh;
    if ($file eq '-')
    $fh = *STDIN;
    else
    open $fh, '<', $file or die "open $file failed: $!";

    while (my $line = <$fh>)
    # ...




    (Technically the <<>> operator also does not allow passing - as an argument to read STDIN, but it is your choice if you want to allow that.)






    share|improve this answer















    The ARGV special filehandle will do this by default. It is also the handle used by readline (aka the <> and <<>> operators) when not given a handle. So this is actually pretty common in Perl scripts.



    #!/usr/bin/env perl
    use 5.022;
    use warnings;
    while (my $line = <<>>)
    # $line from one of the filenames passed as an argument, otherwise STDIN
    # $ARGV is the current filename, or - when reading from STDIN



    You can use the <> operator instead to support older versions of Perl, but the <<>> operator added in Perl 5.22 is a better option for this task if available, because the standard <> operator allows passing strange things like date| to run processes rather than read files.



    For safer filename-only operation while supporting older versions of Perl, you could use ARGV::readonly or emulate the <<>> operator like the following:



    #!/usr/bin/env perl
    use strict;
    use warnings;
    unshift @ARGV, '-' unless @ARGV;
    while (my $file = shift)
    my $fh;
    if ($file eq '-')
    $fh = *STDIN;
    else
    open $fh, '<', $file or die "open $file failed: $!";

    while (my $line = <$fh>)
    # ...




    (Technically the <<>> operator also does not allow passing - as an argument to read STDIN, but it is your choice if you want to allow that.)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 27 at 21:20

























    answered Mar 27 at 17:58









    GrinnzGrinnz

    5,2495 silver badges15 bronze badges




    5,2495 silver badges15 bronze badges















    • It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

      – ikegami
      Mar 27 at 18:37











    • What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

      – ikegami
      Mar 27 at 18:39


















    • It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

      – ikegami
      Mar 27 at 18:37











    • What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

      – ikegami
      Mar 27 at 18:39

















    It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

    – ikegami
    Mar 27 at 18:37





    It will even read from multiple files if multiple files are provided, just like cat, grep, etc.

    – ikegami
    Mar 27 at 18:37













    What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

    – ikegami
    Mar 27 at 18:39






    What the answer doesn't make it clear is that you can use use strict; use warnings; while (my $line = <>) ... if you want to be compatible with older versions of Perl. But don't make setuid scripts (or scripts used by setuid scripts) that use <>.

    – ikegami
    Mar 27 at 18:39














    1















    It appears that the following script fills the bill.



    #!/usr/bin/perl
    use strict;
    use warnings;
    use 5.18.2;
    local $/ = ""; # input record separator: one paragraph at a time
    while (<>)
    print;
    print "n";
    say '-' x 30;



    Example:



    printf '%b' 'dog ncat nratn' > aaa
    try.pl aaa
    cat aaa | try.pl
    try.pl < aaa





    share|improve this answer





























      1















      It appears that the following script fills the bill.



      #!/usr/bin/perl
      use strict;
      use warnings;
      use 5.18.2;
      local $/ = ""; # input record separator: one paragraph at a time
      while (<>)
      print;
      print "n";
      say '-' x 30;



      Example:



      printf '%b' 'dog ncat nratn' > aaa
      try.pl aaa
      cat aaa | try.pl
      try.pl < aaa





      share|improve this answer



























        1














        1










        1









        It appears that the following script fills the bill.



        #!/usr/bin/perl
        use strict;
        use warnings;
        use 5.18.2;
        local $/ = ""; # input record separator: one paragraph at a time
        while (<>)
        print;
        print "n";
        say '-' x 30;



        Example:



        printf '%b' 'dog ncat nratn' > aaa
        try.pl aaa
        cat aaa | try.pl
        try.pl < aaa





        share|improve this answer













        It appears that the following script fills the bill.



        #!/usr/bin/perl
        use strict;
        use warnings;
        use 5.18.2;
        local $/ = ""; # input record separator: one paragraph at a time
        while (<>)
        print;
        print "n";
        say '-' x 30;



        Example:



        printf '%b' 'dog ncat nratn' > aaa
        try.pl aaa
        cat aaa | try.pl
        try.pl < aaa






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 18:09









        Jacob WegelinJacob Wegelin

        914 bronze badges




        914 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55383363%2fcan-a-perl-script-be-written-to-receive-data-from-any-of-1-file-2-stdin-3%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현