The package MIDIwill do this for you, but the exact approach depends on the original contents of the midi file.
A midi file consists of one or more tracks, and each track is a sequence of events on any of sixteen channels, such as Note Off, Note On, Program Change, etc. The last one will change the tool assigned to the channel, and this is what you need to change or add.
- , ( ) , . , , , Program Change .
, Program Change, , . , , .
, Program Change , , . , , , .
, midi , - . MIDI::Opus , ( ) . Program Change ( patch_change) 0 . 40 - - .
, Program Change , - , , .
use strict;
use warnings;
use MIDI;
my $opus = MIDI::Opus->new( { from_file => 'song.mid' } );
my $tracks = $opus->tracks_r;
my $track0_events = $tracks->[0]->events_r;
unshift @$track0_events, ['patch_change', 0, 0, 40];
$opus->write_to_file('newsong.mid');