I don't know perl, but in scheme or python, excatly as you would do it manually:
To get layer2, you can either use its position in the stack, or enumerate all the layers and compare the names.
Code:
# Ensure the layer is alpha-locked (so we don't paint the transparent pixels)
pdb.gimp_layer_set_lock_alpha(layer, True)
# Set foreground to wanted color
pdb.gimp_context_set_foreground((0,0,255))
# Bucket-fill the selection (there should be no selection)
pdb.gimp_drawable_edit_fill(layer,FILL_FOREGROUND)
To get layer2, you can either use its position in the stack, or enumerate all the layers and compare the names.