简体   繁体   中英

Perl: substitute scalar with element of array for that index

I have the following code

    #!/bin/perl

    $prevjob[1]= 'PREVJOB1';
    $prevjob[2]= 'PREVJOB2';
    $prevjob[3]= 'PREVJOB3';
    $line[2]= '(s1&s3)|s2';
    if($line[2]) {
    #this will work for first replacement, but its not working,
            $line[2]=~ s/s([0-9])/s${prevjob[\1]}/;
            print $line[2];
    }

I want to use the numbers in the scalar as indexes and substitute the number with @prevjob's element at that index.

I want to replace s/s([0-9])/s${prevjob[\\1]}/ My expected output is :

(sPREVJOB1&sPREVJOB3)|sPREVJOB2

I figured this out. Looks like i needed s/s([0-9])/s${prevjob[$1]}/;

$1 instead of \\1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM