Skip to main content

コードを別のプログラミング言語に変換する

Copilot Chat は、同じ操作を別のプログラミング言語で実行するようにコードを書き直すのに役立ちます。

あるプログラミング言語から別のプログラミング言語にコードを移行する理由はさまざまです。 各プログラミング言語にはそれぞれの長所と短所があるため、別の言語で使用できる機能を使いたい場合があります。 たとえば、よりパフォーマンスの高い言語や、バグを防ぐために強力な型指定を使う言語にコードを移行することができます。

コードを保守しやすくするために、organization 内でより広く使われている言語にコードを移行することができます。 たとえば、organization 内で Perl などの古い言語を知っている人が少ない場合は、現在も使われている Perl コードを、Python や JavaScript などのより一般に使われている言語に移行することができます。

Copilot は、ある言語から別の言語にコードを変換するのに役立ちます。 スクリプトなどのスタンドアロン ファイルの変換は簡単です。 このプロセスについては、この記事で説明します。

複数のファイルを含むプロジェクトの変換はより複雑なプロセスであり、「Copilot を使ってプロジェクトを別のプログラミング言語に移行する」で説明されています。

シナリオ例

次の Perl スクリプトは、ユーザーにテキスト ファイルのパスの入力を求めるものです。 ユーザーが入力した内容をチェックし、そのパスでテキスト ファイルが見つかった場合は、ファイルの内容の単語数と文字数を出力します。

Perl
#!/usr/bin/perl
use strict;
use warnings;
use File::Spec;
use File::Basename;

print "Please enter the path to a local text file: ";
chomp(my $file_path = <STDIN>);

if ($file_path =~ /[`|;&<>(){}\[\]]/ || !File::Spec->file_name_is_absolute($file_path) && dirname($file_path) ne '.') {
    die "Invalid file path. Please provide a valid path.\n";
}
if (!-e $file_path) {
    die "File not found. Please provide an existing file path.\n";
}

open(my $fh, '<', $file_path) or die "Could not open file '$file_path': $!\n";

my $is_binary = 0;
while (read($fh, my $buffer, 1024)) {
    if ($buffer =~ /[^\x09\x0A\x0D\x20-\x7E]/) {
        $is_binary = 1;
        last;
    }
}
close($fh);

if ($is_binary) {
    die "The file '$file_path' is a binary file. Please provide a text file.\n";
}

open($fh, '<', $file_path) or die "Could not open file '$file_path': $!\n";
my $content = do { local $/; <$fh> };
close($fh);

my $word_count = scalar(split /\s+/, $content);
my $char_count = length($content);

print "The file '$file_path' contains $word_count words and $char_count characters.\n";

プロンプトの例

Tell me how I can convert this Perl script to Typescript. The functionality and output of the new script should be exactly the same as the existing one. Also tell me how to run the new file using Node.

応答の例

Copilot により、次の Typescript コードが生成されます。

Note

Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。

TypeScript
import * as fs from 'fs';
import * as path from 'path';
import * as readline from 'readline';

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Please enter the path to a local text file: ', (filePath) => {
    rl.close();

    if (/[`|;&<>(){}\[\]]/.test(filePath) || (!path.isAbsolute(filePath) && path.dirname(filePath) !== '.')) {
        console.error('Invalid file path. Please provide a valid path.');
        process.exit(1);
    }

    if (!fs.existsSync(filePath)) {
        console.error('File not found. Please provide an existing file path.');
        process.exit(1);
    }

    const fileBuffer = fs.readFileSync(filePath);
    const isBinary = fileBuffer.some(byte => byte < 9 || (byte > 13 && byte < 32) || byte > 126);

    if (isBinary) {
        console.error(`The file '${filePath}' is a binary file. Please provide a text file.`);
        process.exit(1);
    }

    const content = fileBuffer.toString('utf-8');
    const wordCount = content.split(/\s+/).length;
    const charCount = content.length;

    console.log(`The file '${filePath}' contains ${wordCount} words and ${charCount} characters.`);
});

このファイルを wordcount.ts として保存します。

次に、Node.js を使って新しいファイルを実行する方法が Copilot から説明されます。

  1. Node.js をインストールします。 まだインストールしていない場合は、公式 Web サイト (https://nodejs.org/) から Node.js をダウンロードしてインストールします。

  2. TypeScript をインストールします。

    npm install -g typescript
    
  3. TypeScript コードをコンパイルします。

    tsc wordcount.ts
    

    これにより、同じディレクトリ内に wordcount.js ファイルが作成されます。

  4. Node.js を使って JavaScript ファイルを実行します。

    node wordcount.js
    

参考資料