import re


def convert_sql_query_for_perl(raw_query, raw_query_args=None, quote_questions=True):
    """Convert given query from Python style to Perl style

    :type raw_query: str
    :type raw_query_args: list | dict | None
    :type quote_questions: bool
    :rtype str, list[]
    """
    if isinstance(raw_query_args, list):
        return raw_query.replace('%s', "'?'" if quote_questions else "?"), raw_query_args
    elif isinstance(raw_query_args, dict):
        query = raw_query
        for key in raw_query_args.keys():
            query = query.replace('%(' + key + ')s', "'?'" if quote_questions else "?")
        key_by_position = {}
        for key in raw_query_args.keys():
            for position in [m.start() for m in re.finditer(re.escape('%(' + key + ')s'), raw_query)]:
                key_by_position[position] = key
        query_args = []
        for _, key in sorted(key_by_position.items()):
            query_args.append(raw_query_args[key])
        return query, query_args
    else:
        return raw_query, None
