3

I have below syntax used in shell script-

imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall | grep "Black Scholes " | cut-d"=" -f2

Where imp_vol is an executable that prints something. What will be its equivalent in Perl script? For example:

imp_vol -u 110.5 -s 110.9 -p 0.005 -t 0.041 -c 1
    Underlying Price = 110.5
    Strike Price = 110.9
    Price = 0.005
    Time = 0.041
    IsCall = 1
    Black Scholes Vol = 0.0108141

So my purpose is to get the value of Black Scholes Vol in this case as `.0108141 in some variable,as I have to pass that variable in some function again.

Any help will be appreciated.

4 Answers 4

2

There is actually a grep function in perl. It takes an expression or a block as the first argument and a list of strings as the second argument. So you could do this:

my @list = grep(/abcd/, (<>));

See also: grep - perldoc.perl.org

In your specific case you can use the block form to extract the price like this:

imp_vol | perl -e 'print grep { s/\s+Black Scholes Vol = ([-+]?[0-9]*\.?[0-9]+)/$1/ } (<>)'
Sign up to request clarification or add additional context in comments.

Comments

1

If you want all "Black Scholes " like your grep would match

imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall | perl -ne 'print $1 if $_ =~ /Black Scholes .* = (\d+(?:\.\d+)?)/;'

"Black Scholes Vol" exactly

| perl -ne 'print $1 if $_ =~ /Black Scholes Vol = (\d+(?:\.\d+)?)/;'

Comments

0

Use Regexes

while (<>) {
    next if !/abcd/;
    # ...
}

Also, to replace cut, use capture groups, but I can't provide more code because I don"t know your data format.

Comments

0

To execute the command, you can use open to get a filehandle from which you can read its output. You can then use a single regular expression to match the line and extract the value. For example:

my $cmd = "imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall";
open (my $imp, '-|', $cmd) or die "Couldn't execute command: $!";

my $extracted;
while (<$imp>) {
    if (/Black Scholes Vol = (.*)/) {
        $extracted = $1;
    }
}
close $imp;

The parenthesis create a capture group which extracts the value into the special $1 variable.

If you're able to pipe input instead of having to execute the command within Perl, the following one-liner would suffice:

imp_vol ... | perl -ne 'print $1 if /Black Scholes Vol = (.*)/'

2 Comments

@RobEarl-how about usage in current scenario-
See edit. You can either execute the command within the Perl script or pipe its output to the script.

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.