LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   add piping as parameter to a simple perl script (https://www.linuxquestions.org/questions/programming-9/add-piping-as-parameter-to-a-simple-perl-script-927120/)

frater 02-02-2012 04:28 AM

add piping as parameter to a simple perl script
 
I need median in one of my bash scripts.
A friend of mine is encouraging to leave bash alone and start with perl.

On the inet I found this little perl implementation which I now want to use within my bash scripts. A little executable file in /usr/local/sbin/median

Code:

#!/usr/bin/perl
@nums = sort{$a <=> $b} @ARGV;
$med = $nums[($#nums / 2)];

print $med . "\n";

The problem now is that I don't want to pass the parameters on the command line, but I want to pipe them like this.

Code:

# echo '3
> 1
> 3
> 4
> 5
> 2' | median

#

should give the same output as:
Code:

# median 3 1 3 4 5 2
3
#

I would like to have the command-line to take precedence.
If no command line is given it should take STDIN as the parameter.

This could be a (very belated) start with perl for me...
I would really appreciate any input

firstfire 02-02-2012 04:54 AM

Hi.

Code:

#!/usr/bin/perl
@nums = sort{$a <=> $b} <STDIN>;
$med = $nums[($#nums / 2)];

print $med . "\n";

Code:

$ echo  3 1 3 4 5 2 | tr ' ' '\n'| ./median.pl
3

Take a look a this link.

frater 02-02-2012 05:25 AM

Thanks, but do you know how to elegantly support both ways and preferably without needing a "tr ' ' '\n'" ??
The command-line should take precedence

Cedrik 02-02-2012 06:25 AM

Code:

#!/usr/bin/perl

my @nums;

do {
    while(<>) {
        chomp;
        push @nums, split;
    }
} unless $#ARGV > -1;

@nums = @ARGV if $#ARGV > -1;
@nums =  sort {$a <=> $b} @nums;
my $med = $nums[($#nums / 2)];

print $med . "\n";

Code:

echo "1 5 9 82 15" | ./median.pl
9

Code:

echo "
1
5
9
82
15
" | ./median.pl
9

Code:

echo "1 5 9
82 15" | ./median.pl
9

Code:

./median.pl 1 5 9 82 15
9


frater 02-03-2012 05:32 AM

Thanks, thanks, thanks...

Hoping I don't overask, but how would it look if it needs to work like this...
Code:

cat <file> median
median <file>
median 35 3 37 23 12 30

Looking at it now, only the 2 first would be enough.
That's how other functions like sed and grep work:
Code:

cat <file> median
median <file>


firstfire 02-03-2012 06:26 AM

Hi.

Quote:

Looking at it now, only the 2 first would be enough.
That's how other functions like sed and grep work:
That's simpler -- perl has a syntax sugar "<>" for this (read e.g. here)
Code:

#!/usr/bin/perl

my @nums;

while(<>) {
        chomp;
        push @nums, split;
}


@nums =  sort {$a <=> $b} @nums;
my $med = $nums[($#nums / 2)];

print $med . "\n";



All times are GMT -5. The time now is 11:17 AM.