|
| 1 | +package org.perlonjava.perlmodule; |
| 2 | + |
| 3 | +import org.perlonjava.runtime.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * The Vars class is responsible for creating variables in the current package. |
| 7 | + * It mimics the behavior of Perl's vars module, allowing variables to be declared. |
| 8 | + */ |
| 9 | +public class Vars extends PerlModuleBase { |
| 10 | + |
| 11 | + public Vars() { |
| 12 | + super("vars"); |
| 13 | + } |
| 14 | + |
| 15 | + /** |
| 16 | + * Static initializer to set up the Vars module. |
| 17 | + */ |
| 18 | + public static void initialize() { |
| 19 | + Vars vars = new Vars(); |
| 20 | + try { |
| 21 | + vars.registerMethod("import", "importVars", ";$"); |
| 22 | + } catch (NoSuchMethodException e) { |
| 23 | + System.err.println("Warning: Missing vars method: " + e.getMessage()); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Creates the specified variables in the current package. |
| 29 | + * |
| 30 | + * @param args The arguments specifying the variables to create. |
| 31 | + * @param ctx The context in which the variables are being created. |
| 32 | + * @return A RuntimeList representing the result of the variable creation. |
| 33 | + * @throws PerlCompilerException if there are issues with the variable creation process. |
| 34 | + */ |
| 35 | + public static RuntimeList importVars(RuntimeArray args, int ctx) { |
| 36 | + args.shift(); |
| 37 | + |
| 38 | + // Determine the caller's namespace |
| 39 | + RuntimeList callerList = RuntimeScalar.caller(new RuntimeList(), RuntimeContextType.SCALAR); |
| 40 | + String caller = callerList.scalar().toString(); |
| 41 | + |
| 42 | + // Create the specified variables in the caller's namespace |
| 43 | + for (RuntimeScalar variableObj : args.elements) { |
| 44 | + String variableString = variableObj.toString(); |
| 45 | + |
| 46 | + if (variableString.startsWith("$")) { |
| 47 | + // Create a scalar variable |
| 48 | + GlobalVariable.getGlobalVariable(caller + "::" + variableString.substring(1)); |
| 49 | + } else if (variableString.startsWith("@")) { |
| 50 | + // Create an array variable |
| 51 | + GlobalVariable.getGlobalArray(caller + "::" + variableString.substring(1)); |
| 52 | + } else if (variableString.startsWith("%")) { |
| 53 | + // Create a hash variable |
| 54 | + GlobalVariable.getGlobalHash(caller + "::" + variableString.substring(1)); |
| 55 | + } else { |
| 56 | + throw new PerlCompilerException("Invalid variable type: " + variableString); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return new RuntimeList(); |
| 61 | + } |
| 62 | +} |
0 commit comments